Position in Vector using STL

后端 未结 3 795
独厮守ぢ
独厮守ぢ 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:04

    The short answer to what you think you asked with "How do I determine position in std::vector<> given an iterator from it?" is the function std::distance.

    What you probably meant to do, however, was to get the value for the iterator, which you get by dereferencing it:

    using namespace std;
    vector<int>::const_iterator it = min_element(v2.begin(), v2.end());
    cout << "min value at position " << distance(v2.begin(), it) << " is " << *it;
    
    0 讨论(0)
  • 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()));
    
    0 讨论(0)
  • 2021-02-04 05:20

    min_element already gives you the iterator, no need to invoke find (additionally, it's inefficient because it's twice the work). Use distance or the - operator:

    cout << "min value at " << min_element(v2.begin(), v2.end()) - v2.begin();
    
    0 讨论(0)
提交回复
热议问题