c – 将迭代器转换为int

前端之家收集整理的这篇文章主要介绍了c – 将迭代器转换为int前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. int i;
  2. vector<string> names;
  3. string s = "penny";
  4. names.push_back(s);
  5. i = find(names.begin(),names.end(),s);
  6. cout << i;

我试图找到向量中元素的索引.迭代器可以,但我希望它为int.我该怎么做?

解决方法

你可以使用 std::distance这个.
  1. i = std::distance( names.begin(),std::find( names.begin(),s ) );

但是,您可能想要检查您的索引是否超出范围.

  1. if( i == names.size() )
  2. // index out of bounds!

但是,在使用std :: distance之前,可以使用迭代器来做到这一点.

  1. std::vector<std::string>::iterator it = std::find( names.begin(),s );
  2.  
  3. if( it == names.end() )
  4. // not found - abort!
  5.  
  6. // otherwise...
  7. i = std::distance( names.begin(),it );

猜你在找的C&C++相关文章