Alex Rivera | Logout

std::vector and std::min behavior

Asked 2011-12-01T11:24:03.223
13

Why following program is not returning minimum value as 1.

#include <vector>
#include <algorithm>
#include <iostream>

int main ( int argc, char **argv) {
    std::vector<int> test;
    test.push_back(INT_MAX);
    test.push_back(1);

    int min = *(std::min(test.begin(), test.end()));

    std::cout << "Minimum = " << min << std::endl;
}

It returns minimum values as 2147483647

Edit
Report

1 Answer

-1

Be aware that std::vector<T>::end() does NOT give you an iterator to the last element. It returns an iterator pointing BEHIND the last element.
If you want to address the first and last element with iterator logic you need to use (test.begin(), test.end()-1).

answered 2011-12-01T11:56:06.330

Your Answer