简体   繁体   English

std :: vector和std :: min行为

[英]std::vector and std::min behavior

Why following program is not returning minimum value as 1. 为什么以下程序没有将最小值返回为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 它返回minimum 2147483647

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. 返回两个参数中较小的一个返回a和b中较小的一个。 If both are equivalent, a is returned. 如果两者都是等价的,则返回a。

std::min_element

Returns an iterator pointing to the element with the smallest value in the range [first,last). 返回指向范围[first,last]中具有最小值的元素的迭代器。 The comparisons are performed using either operator< for the first version, or comp for the second; 比较是使用operator <作为第一个版本,或comp作为第二个版本; An element is the smallest if no other element compares less than it (it may compare equal, though). 如果没有其他元素比它小,那么元素是最小的(尽管它可能比较相等)。

Be aware that std::vector<T>::end() does NOT give you an iterator to the last element. 请注意, std::vector<T>::end()不会为最后一个元素提供迭代器。 It returns an iterator pointing BEHIND the last element. 它返回一个指向BEHIND最后一个元素的迭代器。
If you want to address the first and last element with iterator logic you need to use (test.begin(), test.end()-1) . 如果要使用迭代器逻辑寻址第一个和最后一个元素,则需要使用(test.begin(), test.end()-1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM