我有多个 int 集。 C++语言
multiset<int>t;
我需要找到大于等于 val 的第一个元素的位置。我为此使用了 lower_bound
multiset<int>::iterator it= lower_bound(t[n].begin(), t[n].end(), val);
但是找不到从multi set开始的相对位置。 正如 Cplusplus.com 建议使用.. 作为 vector 。
// lower_bound/upper_bound example
#include <iostream> // std::cout
#include <algorithm> // std::lower_bound, std::upper_bound, std::sort
#include <vector> // std::vector
int main () {
int myints[] = {10,20,30,30,20,10,10,20};
std::vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20
std::sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30
std::vector<int>::iterator low,up;
low=std::lower_bound (v.begin(), v.end(), 20); // ^
up= std::upper_bound (v.begin(), v.end(), 20); // ^
std::cout << "lower_bound at position " << (low- v.begin()) << '\n';
std::cout << "upper_bound at position " << (up - v.begin()) << '\n';
return 0;
}
我可以在多组中做吗? 另一个问题是:我可以合并到像下面所示的 vector 这样的多集吗,v1、v2、v 是 vector ?
merge(v1.begin(),v1.end(),v2.begin(),v1.end(),back_inserter(v))
最佳答案
获取两个迭代器之间距离的通用方法是调用 std::distance .
auto it = std::lower_bound(t[n].begin(), t[n].end(), val);
const auto pos = std::distance(t[n].begin(), it);
关于c++ - 多集索引查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28009210/