简体   繁体   English

使用STL在Vector中的位置

[英]Position in Vector using STL

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 giving me the value. 我试图使用STL查找算法(和min_element算法)找到向量中最小值的位置,但不是返回postion,它只是给我值。 Eg, if the minimum value is it, is position will be returned as 8 etc. What am I doing wrong here? 例如,如果它是最小值,那么位置将返回为8等。我在这里做错了什么?

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

min_element already gives you the iterator, no need to invoke find (additionally, it's inefficient because it's twice the work). min_element已经为你提供了迭代器,不需要调用find (另外,它的效率很低,因为它是工作的两倍)。 Use distance or the - operator: 使用distance-运算符:

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

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: 由于你正在迭代一个向量,你可以使用减号运算符,正如Konrad所说:

 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: 但我建议使用std :: distance算法,它更灵活,适用于所有标准容器:

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

The short answer to what you think you asked with "How do I determine position in std::vector<> given an iterator from it?" 简单回答你认为你问的问题“我如何确定std::vector<>给定迭代器?” is the function std::distance . 是函数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;

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

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