将迭代器转换为int

问题描述

|
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
的开头之间将ѭ11
find
(本质上是在
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;
    

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...