相关疑难解决方法(0)

检查 unordered_set 是否包含其他 unordered_set 中的所有元素 - C++

我是 C++ 新手,被要求将 Java 程序转换为 C++。我正在尝试编写一种方法来检查 unordered_set 中的所有元素是否存在于另一个 unordered_set 中。我发现下面的示例使用 hash_set,但 hash_set 已弃用,建议现在使用 unordered_set。

// returns true if one contains all elements in two
bool SpecSet::containsAll(hash_set<Species*> one, hash_set<Species*> two) {
   sort(one.begin(), one.end());
   sort(two.begin(), two.end());
   return includes(one.begin(), one.end(), two.begin(), two.end());
}
Run Code Online (Sandbox Code Playgroud)

所以我需要一种使用 unordered_set 来做到这一点的方法。排序不适用于无序集,并且查找速度很重要,因此我不想使用有序集。

bool SpecSet::containsAll(unordered_set<Species*> one, unordered_set<Species*> two) {

   return ?;
}
Run Code Online (Sandbox Code Playgroud)

我真的很感谢您提供一些帮助来有效地做到这一点。

编辑:我想这会起作用。看来除了一分为二循环之外,没有更有效的方法了。

bool SpecSet::containsAll(unordered_set<Species*> one, unordered_set<Species*> two) {
   if(two.size() > one.size())
   {
      return false;
   }

   for(Species *species : two)
   {
      if(one.find(species) == one.end())
      {
         return false;
      }
   } …
Run Code Online (Sandbox Code Playgroud)

c++ unordered-set

6
推荐指数
1
解决办法
3680
查看次数

两个unordered_set相交的C ++库方法

我有两个unordered_set并想要它们的交集。我找不到执行此操作的库函数。

本质上,我想要的是:

unordered_set<int> a = {1, 2, 3};
unordered_set<int> b = {2, 4, 1};

unordered_set<int> c = a.intersect(b); // Should be {1, 2}
Run Code Online (Sandbox Code Playgroud)

我可以做类似的事情

unordered_set<int> c;
for (int element : a) {
  if (b.count(element) > 0) {
    c.insert(element);
  }
}
Run Code Online (Sandbox Code Playgroud)

但我认为应该有更方便的方法吗?如果没有,有人可以解释为什么吗?我知道有set_intersection,但这似乎只对向量起作用?

谢谢

c++ stl

4
推荐指数
1
解决办法
1301
查看次数

如何提高C ++中的std :: set_intersection性能?

在C ++中使用std :: set和Python中使用set()进行实验期间,我遇到了无法解释的性能问题。在C ++中设置交集至少要比Python慢​​3倍。

因此,有人能指出我可以对C ++代码进行的优化和/或解释Python如何更快地做到这一点吗?

我希望他们都可以在set有序的情况下使用O(n)复杂度的相似算法。但是Python可能会做一些优化,以使其系数变小。

set_bench.cc

#include <iostream>
#include <set>
#include <algorithm>
#include <iterator>
#include <chrono>
#include <functional>
#include <thread>

void elapsed(std::function<void()> f, const std::string& s)
{
    auto start = std::chrono::steady_clock::now();
    f();
    std::chrono::duration<double> elapsed = std::chrono::steady_clock::now() - start;
    std::cout << s << " " << elapsed.count() << " seconds" << std::endl;
}

template <typename T>
void fill_set(std::set<T>& s, T start, T end, T step)
{
    for (T i = start; i < end; i += step) { …
Run Code Online (Sandbox Code Playgroud)

c++ performance hashtable set

4
推荐指数
1
解决办法
375
查看次数

标签 统计

c++ ×3

hashtable ×1

performance ×1

set ×1

stl ×1

unordered-set ×1