问题描述
|
int i;
vector<string> names;
string s = \"penny\";
names.push_back(s);
i = find(names.begin(),names.end(),s);
cout << i;
我正在尝试查找向量中元素的索引。 iterators
可以,但我要as2ѭ。我该怎么做?
解决方法
您可以为此使用
std::distance
。
i = std::distance( names.begin(),std::find( names.begin(),names.end(),s ) );
但是,您可能需要检查索引是否没有超出范围。
if( i == names.size() )
// index out of bounds!
不过,在使用std :: distance之前,使用迭代器执行此操作可能更清晰。
std::vector<std::string>::iterator it = std::find( names.begin(),s );
if( it == names.end() )
// not found - abort!
// otherwise...
i = std::distance( names.begin(),it );
,std::vector<string>::iterator it = std::find(names.begin(),s);
if (it != names.end()) {
std::cout << std::distance(names.begin(),it);
} else {
// ... not found
}
,尝试
i = (find( names.begin(),s ) - names.begin());
编辑:
虽然您应该考虑使用vector :: size_type而不是int。
,我对您的代码的假设:
using std::vector;
using std::cout;
using std::string;
如果我的假设是正确的,那么您可以在vector
到iterator
的开头之间将ѭ11find
(本质上是在vector
中可以找到该元素的索引):
using std::distance;
像这样
vector<string>::iterator i = find(names.begin(),s);
if (i != names.end())
{
cout << \"Index \" << std::distance(names.begin(),i);
}
else
{
cout << s << \"not found\";
}
,您可以取消引用迭代器
int i = *name;