如何获取vector中目标元素的位置?已试用std::binary_search仅能判断存在性
适合的查找函数推荐(返回元素位置)
当然有啦!既然你已经在使用std::binary_search,说明你的vector是有序的——这时候用下面这些返回迭代器(即元素位置)的标准库函数,既能判断元素是否存在,又能直接拿到位置来做插入/删除操作,完美适配你的需求:
1. std::lower_bound(最常用,适合有序容器)
这个函数会用二分查找(和binary_search效率一样,都是O(log n))返回第一个不小于目标值的元素的迭代器:
- 如果目标元素存在,返回的迭代器指向第一个匹配的元素;
- 如果不存在,返回的迭代器正好是你应该插入目标的位置(能保持vector的有序性)。
示例代码:
#include <vector> #include <algorithm> #include <iostream> int main() { std::vector<int> arr = {10, 20, 30, 98, 100}; int target = 98; // 获取迭代器 auto it = std::lower_bound(arr.begin(), arr.end(), target); // 检查是否找到目标 if (it != arr.end() && *it == target) { // 计算索引(迭代器转索引用std::distance) int index = std::distance(arr.begin(), it); std::cout << "找到元素 " << target << ",位置索引:" << index << std::endl; // 执行删除操作 arr.erase(it); // 或者执行插入操作(比如在目标位置前插入97) // arr.insert(it, 97); } else { int insert_pos = std::distance(arr.begin(), it); std::cout << target << " 不存在,适合插入的位置索引:" << insert_pos << std::endl; } return 0; }
2. std::upper_bound(处理重复元素场景)
如果你的vector里有重复的目标元素,std::upper_bound会返回第一个大于目标值的元素的迭代器。配合std::lower_bound,就能拿到所有匹配元素的区间[first, last):
auto first_match = std::lower_bound(arr.begin(), arr.end(), target); auto last_match = std::upper_bound(arr.begin(), arr.end(), target); if (first_match != last_match) { int count = std::distance(first_match, last_match); std::cout << "找到 " << count << " 个" << target << "元素" << std::endl; // 删除所有匹配的元素 arr.erase(first_match, last_match); }
3. std::find(适合无序容器)
如果你的vector是无序的,就不能用二分查找了,这时候用std::find做线性查找(O(n)效率),返回第一个匹配元素的迭代器:
auto it = std::find(arr.begin(), arr.end(), target); if (it != arr.end()) { int index = std::distance(arr.begin(), it); std::cout << "找到元素,位置索引:" << index << std::endl; } else { std::cout << target << " 不存在于vector中" << std::endl; }
小提示
其实std::binary_search内部就是通过std::lower_bound实现的,所以直接用lower_bound可以一步到位,同时完成“存在性判断”和“获取位置”两个需求,比先调用binary_search再查找位置更高效哦~
内容的提问来源于stack exchange,提问作者Shantanu
相关产品推荐
相关产品推荐

