如何在 C++ 中将向量迭代器转换为 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26995725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert vector iterator to int in C++
提问by jason
I am looking for an element in a C++ vector, and when I find it, I want to get found element's index in a numerical form(integer, float).
我正在寻找 C++ 向量中的一个元素,当我找到它时,我想以数字形式(整数,浮点数)获取找到的元素的索引。
My naive attempt is this :
我天真的尝试是这样的:
int x;
int index;
vector<int> myvector;
vector<int>::iterator it;
it = find(myvector.begin(), myvector.end(), x);
index = (int) * it;
This code is giving error. Can you tell me how I can convert iterator to int(if possible), or can you tell me how I can get found element's index in other way? Thanks.
此代码给出错误。您能告诉我如何将迭代器转换为 int(如果可能),或者您能告诉我如何以其他方式获取已找到元素的索引吗?谢谢。
回答by Vlad from Moscow
You need to use standard function std::distance
您需要使用标准功能 std::distance
index = std::distance( myvector.begin(), it );
if ( index < myvector.size() )
{
// do something with the vector element with that index
}
Try always to use std::distance
even with random access iterators. This function is available in the new and old C++ Standards.
std::distance
即使使用随机访问迭代器,也要始终尝试使用。此函数在新旧 C++ 标准中都可用。
回答by Mike Seymour
If you want the index of the found element, then that's the distance from the start of the sequence:
如果您想要找到元素的索引,那么这就是与序列开头的距离:
index = it - myvector.begin();
or, since C++11,
或者,从 C++11 开始,
index = std::distance(myvector.begin(), it);
which will work with any forward iterator type, not just random-access ones like those from a vector.
它适用于任何前向迭代器类型,而不仅仅是像向量那样的随机访问类型。
回答by Cory Kramer
You just dereference the iterator like this
您只需像这样取消引用迭代器
index = *it;
However you should first see if you actually found something
但是你应该首先看看你是否真的找到了一些东西
it = find(myvector.begin(), myvector.end(), x);
if (it != myvector.end())
{
index = *it;
}
To find the index in that the match was found, you can use subtraction of the found pointer from the start of the vector.
要找到找到匹配项的索引,您可以使用从向量开头减去找到的指针。
it = find(myvector.begin(), myvector.end(), x);
if (it != myvector.end())
{
index = it - myvector.begin(); // Index from start of vector
}
Also, hopefully in your actual code you defined x
, as in the snippet you showed x
is uninitialized so this will result in undefined behavior.
此外,希望在您定义的实际代码中x
,因为在您显示的代码段x
中未初始化,因此这将导致未定义的行为。