Avinash
Avinash

Reputation: 13257

std::vector and std::min behavior

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

Upvotes: 13

Views: 19552

Answers (2)

mrolf
mrolf

Reputation: 35

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).

Upvotes: -1

FailedDev
FailedDev

Reputation: 26930

You could try this:

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

std::min

Return the lesser of two arguments Returns the lesser of a and b. If both are equivalent, a is returned.

std::min_element

Returns an iterator pointing to the element with the smallest value in the range [first,last). The comparisons are performed using either operator< for the first version, or comp for the second; An element is the smallest if no other element compares less than it (it may compare equal, though).

Upvotes: 48

Related Questions