- int i;
- vector<string> names;
- string s = "penny";
- names.push_back(s);
- i = find(names.begin(),names.end(),s);
- cout << i;
我试图找到向量中元素的索引.迭代器可以,但我希望它为int.我该怎么做?
解决方法
你可以使用
std::distance
这个.
- i = std::distance( names.begin(),std::find( names.begin(),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 );