微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 将迭代器转换为int

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 );

原文地址:https://www.jb51.cc/c/113660.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐