c++ - 多集索引查找

标签 c++ multiset

我有多个 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/

相关文章:

c++ - block 非专用模板 C++

c++ - 在 multiset 中,代码没有进入比较函数并抛出错误

list - 当不需要保留顺序时,可以编码为更少的位吗?

c++ - C/C++ 中双引号字符的备用字符组合是什么?

c++ - 需要帮助来修复我的代码以执行特定的逻辑

list - 存储多重集/无序列表的节省空间的方法

c++ - 保持排序的数据结构,允许 log N 插入时间,并且可以返回我在 log N 中查找的元素的索引

c++ - 如何在 qt main() 中运行 post 请求

c++ - std::ostringstream 未返回有效字符串

c++ - 循环依赖...怎么解决?