如何在C ++中将向量迭代器转换为int [英] How to convert vector iterator to int in C++
本文介绍了如何在C ++中将向量迭代器转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找C ++向量中的元素,当我找到它时,我想以数字形式(整数,浮点数)获取元素的索引.
I am looking for an element in a C++ vector, and when I find it, I want to get found element's index in a numerical form(integer, float).
我的天真尝试是这样
int x;
int index;
vector<int> myvector;
vector<int>::iterator it;
it = find(myvector.begin(), myvector.end(), x);
index = (int) * it;
此代码给出了错误.您能否告诉我如何将迭代器转换为int(如果可能),或者可以告诉我如何以其他方式获取元素的索引?谢谢.
This code is giving error. Can you tell me how I can convert iterator to int(if possible), or can you tell me how I can get found element's index in other way? Thanks.
推荐答案
您需要使用标准函数std::distance
index = std::distance( myvector.begin(), it );
if ( index < myvector.size() )
{
// do something with the vector element with that index
}
即使随机访问迭代器,也请尝试始终使用std::distance
.在新的和旧的C ++标准中都可以使用此功能.
Try always to use std::distance
even with random access iterators. This function is available in the new and old C++ Standards.
这篇关于如何在C ++中将向量迭代器转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文