如何查找C++ vector中目标值的首个与最后一个索引?
解决查找目标值首个和最后一个索引的问题
嘿,看来你已经搞定了第一个索引的查找,最后一个索引的问题我来帮你捋清楚!
首先,咱们先说说你现有代码里的错误:你写的int lastindex = distance(v.end(), it);完全找错了方向——distance是计算从第一个迭代器到第二个迭代器的距离,v.end()是容器的尾后迭代器(在最后一个元素的后面),从它到第一个找到的it的距离是负数,这显然不是你要的最后一个匹配元素的索引,后面的lastindex - index自然也不对。
下面给你两种靠谱的方法来获取最后一个索引:
方法一:使用反向迭代器
反向迭代器可以从容器末尾往前遍历,用find找到第一个(也就是原容器里的最后一个)匹配元素,再转成正向索引:
// 从末尾开始找第一个匹配的元素(即原容器的最后一个) vector<int>::reverse_iterator last_r_it = find(v.rbegin(), v.rend(), 1); if (last_r_it != v.rend()) { // 反向迭代器的base()方法会返回对应的正向迭代器,但指向的是反向迭代器位置的下一个元素 // 所以要减1才能得到原容器中正确的索引 int last_index = distance(v.begin(), last_r_it.base()) - 1; }
方法二:使用find_end算法
find_end是STL专门用来查找最后一次出现的元素(或子序列)的算法,对于单个元素来说,用法很简单:
int target = 1; // 前两个参数是容器范围,后两个是要查找的单个元素的范围(地址+1形成长度为1的序列) vector<int>::iterator last_it = find_end(v.begin(), v.end(), &target, &target + 1); if (last_it != v.end()) { int last_index = distance(v.begin(), last_it); }
完整修正后的代码
把两种方法整合到你的代码里,最终版本如下:
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> v = {1,2,3,1,6,2,1}; int target = 1; vector<int>::iterator first_it = find(v.begin(), v.end(), target); if (first_it != v.end()) { cout << "Element Found" << endl; int first_index = distance(v.begin(), first_it); // 这里用反向迭代器的方法,你也可以换成find_end的写法 vector<int>::reverse_iterator last_r_it = find(v.rbegin(), v.rend(), target); int last_index = distance(v.begin(), last_r_it.base()) - 1; cout << "Index of first element in vector : " << first_index << ", last element index: " << last_index << endl; } else { cout << "Element Not Found" << endl; } return 0; }
运行这段代码,就能得到你要的结果:首个索引=0,最后索引=6啦!
内容的提问来源于stack exchange,提问作者Jackson750
相关产品推荐
相关产品推荐

