【问题标题】:Understanding boost::disjoint_sets_with_storage理解 boost::disjoint_sets_with_storage
【发布时间】:2016-07-11 16:48:38
【问题描述】:

我试图理解boost::disjoint_sets_with_storage,但即使是最简单的例子也不起作用,我不明白为什么。

#include <boost/pending/disjoint_sets.hpp>

int main(){
    boost::disjoint_sets_with_storage<> union_find;
    union_find.make_set(1);
    //..
}

上面的代码可以编译,但会产生段错误。我想使用整数作为元素,但在boost documentation 中没有“元素”模板参数,所以我假设它推断类型。但是,问题是什么?谢谢

【问题讨论】:

标签: c++ c++11 boost disjoint-sets union-find


【解决方案1】:

我对使用它还不是 100% 有信心,但我得到了一个示例,我在这里尝试对其进行简化。 我认为如果你可以简单地使用从 0 到 n-1 的整数,它们要么在同一个集合中,要么不在同一个集合中。

#include <iostream>
#include <boost/pending/disjoint_sets.hpp>
#include <vector>
typedef boost::disjoint_sets_with_storage<> Uf;

std::vector<pair<int,int>> same_set;
// fill the vector with number pairs between 0 and n-1 where
// n is the number of unique elements in the set
// ...
int n = ...; // n is the number of unique set elements

Uf union_find_set(n); // creates the structure with numbers 0 to n-1
// in seperate sets.  -> one set is for 0, one set for 1, ...

for (auto same : same_set) {
    union_find_set.union_set(same.first, same.second);
}
// union_find_set now contains sets with the numbers
// 0 to n-1 according to which sets should be combined
// given in the vector same_set.

// check whether two elements are in the same set, i.e. 0 and 2:
std::cout << union_find_set.find_set(0, 2);

【讨论】:

  • union_find_set.find_set(...) 只接受一个参数并返回参数的集合。
猜你喜欢
  • 2011-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-10
  • 2018-02-18
  • 2020-12-29
  • 2012-06-27
相关资源
最近更新 更多