C++ 将迭代器转换为 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6136362/
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
Convert iterator to int
提问by thetux4
int i;
vector<string> names;
string s = "penny";
names.push_back(s);
i = find(names.begin(), names.end(), s);
cout << i;
I'm trying to find index of an element in vector. It's ok with iterators
, but I want it as int
. How can I do it?
我正在尝试查找向量中元素的索引。没关系iterators
,但我想要它作为int
. 我该怎么做?
回答by CB Bailey
You can use std::distance
for this.
您可以std::distance
为此使用。
i = std::distance( names.begin(), std::find( names.begin(), names.end(), s ) );
You will probably want to check that your index isn't out of bounds, though.
不过,您可能想要检查您的索引是否超出范围。
if( i == names.size() )
// index out of bounds!
It's probably clearer to do this with the iterator before using std::distance, though.
不过,在使用 std::distance 之前使用迭代器执行此操作可能更清楚。
std::vector<std::string>::iterator it = std::find( names.begin(), names.end(), s );
if( it == names.end() )
// not found - abort!
// otherwise...
i = std::distance( names.begin(), it );
回答by Georg Fritzsche
std::vector<string>::iterator it = std::find(names.begin(), names.end(), s);
if (it != names.end()) {
std::cout << std::distance(names.begin(), it);
} else {
// ... not found
}
回答by iolo
try
尝试
i = (find( names.begin(), names.end(), s ) - names.begin());
Edit: Although you should consider using vector::size_type instead of an int.
编辑:尽管您应该考虑使用 vector::size_type 而不是 int。
回答by Johnsyweb
Assumptions that I am making about your code:
我对您的代码所做的假设:
using std::vector;
using std::cout;
using std::string;
If my assumptions are correct, then you can find
the distance
between the beginning of the vector
and the iterator
(essentially the index into the vector
at which you can find such element):
如果我的假设是正确的,那么你可以find
在distance
的开始之间vector
和iterator
(基本的索引,vector
在这里您可以找到这样的元素):
using std::distance;
Like so...
像这样...
vector<string>::iterator i = find(names.begin(), names.end(), s);
if (i != names.end())
{
cout << "Index " << std::distance(names.begin(), i);
}
else
{
cout << s << "not found";
}
回答by shaina
You can just dereference your iterator
您可以取消引用您的迭代器
int i = *name;