Position in Vector using STL

后端 未结 3 799
独厮守ぢ
独厮守ぢ 2021-02-04 04:22

im trying to locate the position of the minimum value in a vector, using STL find algorithm (and the min_element algorithm), but instead of returning the postion, its just givin

3条回答
  •  死守一世寂寞
    2021-02-04 05:16

    Both algorithms you're using return iterators. If you dereference an iterator, you get the object which is "pointed" by this iterator, which is why you print the value and not the position when doing

    cout << "min value at position " << *find(v2.begin(), v2.end(), value);
    

    An iterator can be seen as a pointer (well, not exactly, but let's say so for the sake of simplicity); therefore, an iterator alone can't give you the position in the container. Since you're iterating a vector, you can use the minus operator, as Konrad said:

    cout << "min value at " << min_element(v2.begin(), v2.end()) - v2.begin();
    

    but I would recommend using the std::distance algorithm, which is much more flexible and will work on all standard containers:

    cout << "min value at " << distance(v2.begin(), min_element(v2.begin(), v2.end()));
    

提交回复
热议问题