Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector and std::min behavior

Tags:

c++

stl

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

like image 377
Avinash Avatar asked Dec 01 '11 11:12

Avinash


1 Answers

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

like image 191
FailedDev Avatar answered Oct 22 '22 23:10

FailedDev