多集索引查找

Multiset Index Finding

本文关键字:索引查找      更新时间:2023-10-16

我有一组多组 int .C++

multiset<int>t;

我需要找到第一个大于等于 val 的元素的位置。我为此使用了lower_bound

multiset<int>::iterator it= lower_bound(t[n].begin(), t[n].end(), val);

但找不到多集开头的相对位置。正如 Cplusplus.com 建议使用..为矢量。

// 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;
}

我可以在多套中做到这一点吗.. ?另一个问题是:我可以合并到多集像下面所示的向量,v1,v2,v 是向量吗?

merge(v1.begin(),v1.end(),v2.begin(),v1.end(),back_inserter(v))

获取两个迭代器之间距离的通用方法是调用 std::d istance。

auto it = std::lower_bound(t[n].begin(), t[n].end(), val);
const auto pos = std::distance(t[n].begin(), it);

对于std::multiset,成员类型iteratorconst_iterator是双向迭代器类型。双向迭代器不支持算术运算符 + 和 -(有关详细信息,请查看 cpp首选项)。

std::distance可用于计算两个迭代器之间的元素数。

std::distance 使用 operator- 来计算元素数(如果参数是随机访问迭代器)。否则,它将重复使用增加运算符(运算符++)。

这是从 cppreference 稍微更改的代码片段。

#include <iostream>
#include <set>
int main ()
{
  std::multiset<int> mymultiset;
  std::multiset<int>::iterator itlow, itup;
  for (int i = 1; i < 8; i++) mymultiset.insert(i * 10); // 10 20 30 40 50 60 70
  itlow = mymultiset.lower_bound(30);
  itup = mymultiset.upper_bound(40);
  std::cout << std::distance(mymultiset.begin(), itlow) << std::endl;
  std::cout << std::distance(mymultiset.begin(), itup) << std::endl;
  mymultiset.erase(itlow, itup); // 10 20 50 60 70
  std::cout << "mymultiset contains: ";
  for (std::multiset<int>::iterator it = mymultiset.begin(); it != mymultiset.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << 'n';
  return 0;
}

输出

2
4
mymultiset contains:  10 20 50 60 70

您可以将std::multisetstd::multiset::insert成员函数合并,如下所示;

#include <iostream>
#include <set>
int main ()
{
  std::multiset<int> mset1;
  std::multiset<int> mset2;
  for (int i = 1; i < 8; i++) mset1.insert(i * 10); // 10 20 30 40 50 60 70
  for (int i = 1; i < 8; i++) mset2.insert(i * 10); // 10 20 30 40 50 60 70
  mset1.insert(mset2.begin(), mset2.end());
  std::cout << "mset1 contains: ";
  for (std::multiset<int>::iterator it = mset1.begin(); it != mset1.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << 'n';
  return 0;
}

输出

mset1 contains:  10 10 20 20 30 30 40 40 50 50 60 60 70 70