【问题标题】:C++ How can we insert std::set inside std::vector<std::unordered_set>C++ 我们如何在 std::vector<std::unordered_set> 中插入 std::set
【发布时间】:2014-08-10 13:55:05
【问题描述】:

如果我们有

std::set<int > a;
std::vector<std::unordered_set<int>> b;

然后我们在b 中插入a

方法一:我们可以这样做:

std::set<int > a;
std::vector<std::unordered_set<int>> b (a.begin(), a.end());

方法2,我们不能这样做吗?

std::set<int > a;
std::vector<std::unordered_set<int>> b;
b.insert(a.begin(), a.end()); 

这个错误是什么意思?

错误 C2664: 'std::_Vector_iterator,std::equal_to<_kty>,std::allocator<_kty>>>>> std::vector,std::equal_to<_kty>,std::allocator<_kty>>,std::allocator<_ty>>::insert(std::_Vector_const_iterator,std::equal_to<_kty>,std::分配器<_kty>>>>,无符号 int,const _Ty &)' : 无法将参数 1 从 'std::_Tree_const_iterator>>' 到 'std::_Vector_const_iterator,std::equal_to<_kty>,std::allocator<_kty>>>>>' IntelliSense:没有重载函数实例“std::vector<_ty _alloc>::insert [with _Ty=std::unordered_set, std::equal_to, std::allocator>, _Alloc=std::allocator, std::equal_to, std::allocator>>]" 匹配参数列表 参数类型是: (std::_Tree_const_iterator>>, std::_Tree_const_iterator>>) 对象类型为:std::vector、std::equal_to、std::allocator>、 标准::分配器, std::equal_to, std::allocator>>>

如果我们需要将b 处理为全局unordered_set,解决方案是什么?

【问题讨论】:

  • 我不太清楚您要做什么。你期待b 的内容是什么?
  • 错误表示set不是unordered_set...
  • 错误消息中的哪些内容对您来说特别不清楚?
  • 您不能将b 视为全局unordered_set,因为它不是一个集合。它是一个完整的集合向量。您的意思是在向量中添加 a 的内容吗,例如b[0].insert(...)?或者在向量中添加一个新集合,其中新集合的内容来自a ?
  • @Sandy:试试b.emplace_back(a.begin(), a.end());

标签: c++


【解决方案1】:

对于方法1,您可以如下:

std::set<int> a{ 1, 2, 3, 4, 5};
std::vector<std::unordered_set<int>> b(1, std::unordered_set<int>(a.begin(), a.end()));

LIVE DEMO

对于方法二,你可以这样做:

std::set<int> a{ 1, 2, 3, 4, 5};
std::vector<std::unordered_set<int>> b(1);
b[0].insert(a.begin(), a.end());

LIVE DEMO

或者作为:

std::set<int> a{ 1, 2, 3, 4, 5};
std::vector<std::unordered_set<int>> b;
b.push_back({a.begin(), a.end()});

LIVE DEMO

或者像@Ben Voigt 建议的那样:

  std::set<int> a{ 1, 2, 3, 4, 5};
  std::vector<std::unordered_set<int>> b;
  b.emplace_back(a.begin(), a.end());

LIVE DEMO

【讨论】:

  • 它的工作原理很像push_back,只是它避免了对要添加的元素进行额外的复制。
  • @BenVoigt 我知道它将rvalue 引用作为输入,但我不确定它是否适用于初始化程序。
  • 它不需要使用初始化列表,所有参数都被转发。
  • @BenVoigt 我尝试这样做,但出现错误coliru.stacked-crooked.com/a/b90c39609aec6f64,我发现了这个相关问题:stackoverflow.com/questions/20391632/…
  • b.emplace_back(a.begin(), a.end()); 为我工作。正如我所说,所有参数都是转发的,它们不需要放入初始化列表中。
【解决方案2】:

对于方法2:

vector::insert() 没有重载需要两个迭代器。试试这个:

b.insert( b.begin(), { a.begin(), a.end() } )

【讨论】:

  • 不应该是b.insert( b.begin(), { a.begin(), a.end() } ),因为a 迭代器定义了要插入的单个元素(一组int)?
  • @BenVoigt 我正在关注这个重载:template&lt; class InputIt &gt; void insert( iterator pos, InputIt first, InputIt last);
  • 你不能那样做。 *first 是一个int,但向量不包含int,它包含unordered_set&lt;int&gt;。
猜你喜欢
  • 2015-10-11
  • 2018-03-12
  • 1970-01-01
  • 2021-05-30
  • 2013-08-18
  • 2018-05-31
  • 1970-01-01
  • 2016-02-04
  • 1970-01-01
相关资源
最近更新 更多