c++ - 创建对 vector 的问题

标签 c++ algorithm stl

我正在尝试创建一个名为 Disjoint Set 的数据结构。看理论我想到的是这样的:

std::vector<std::pair<int,std::set<int>>> DisjointSet;
for(auto i=0;i<10;++i) DisjointSet.push_back( std::make_pair(i,std::set<int>().insert(i)));

但是这段代码给出的内容超出了我的理解范围,所以这是制作不相交集的好设计。另外,我该如何摆脱这些错误?

最佳答案

set::insert 不返回集合本身。您需要预先创建集合,insert 然后在make_pair 中使用它。使用 move 复制几乎没有开销:

std::vector< std::pair<int,std::set<int> > > DisjointSet;
for(auto i=0;i<10;++i) {
  std::set<int> tmp; tmp.insert(i);
  DisjointSet.push_back( std::make_pair(i,std::move(tmp)));
}

关于c++ - 创建对 vector 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7031462/

相关文章:

java - 从 N 叉树中随机选择一个节点

c++ - Nuke - Matrix4 相机约束锁 Z 旋转

c++ - boost::accumulators::rolling_mean 返回不正确的平均值

c++ - 将 C++ 程序与 Fortran 库链接时对 _rpoly_ 的 undefined reference

c++ - 有标准的 C++ 哈希容器吗?

c++ - 标准库或编译器在哪里利用 noexcept move 语义( vector 增长除外)?

C++ STL 映射异常。 (不可变树的根)

c++ - QTableWidget内存违规

algorithm - 找出数组中元素之间的最小差异

为设置的表格宽度计算可变列宽的算法