C++ 我们如何在 std::vector<std::unordered_set> 中插入 std::set

标签 c++

如果我们有

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

然后我们将 a 插入 b

方法一:我们可以做到:

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

方法二,我们做不到吗?

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

这个错误是什么意思?

error 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::allocator<_Kty>>>>>,unsigned int,const _Ty &)' : cannot convert argument 1 from 'std::_Tree_const_iterator>>' to 'std::_Vector_const_iterator,std::equal_to<_Kty>,std::allocator<_Kty>>>>>' IntelliSense: no instance of overloaded function "std::vector<_Ty, _Alloc>::insert [with _Ty=std::unordered_set, std::equal_to, std::allocator>, _Alloc=std::allocator, std::equal_to, std::allocator>>]" matches the argument list argument types are: (std::_Tree_const_iterator>>, std::_Tree_const_iterator>>) object type is: std::vector, std::equal_to, std::allocator>, std::allocator, std::equal_to, std::allocator>>>

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

最佳答案

对于方法一,您可以按如下方式进行:

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

关于C++ 我们如何在 std::vector<std::unordered_set> 中插入 std::set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24316568/

相关文章:

c++ - 在具有相同参数和兼容返回值的 C++ 方法指针之间进行转换

c++ - 虚拟继承的优势

c++ - (CGAL) 获取AABB树生成的bounding cube做碰撞检测

c++ - 程序在错误的位置查找 libstdc++.so.6,似乎忽略了 LD_LIBRARY_PATH

c++ - IEEE 754-2008(密集十进制)的可用实现

c++ - 为什么未使用的参数不会被编译器丢弃?

c++ - usleep 是否创建线程取消点?

c++ - 为什么当递归函数结果相乘时,g++仍然优化尾递归?

c++ - 客户端服务器 C++ 序列化

c++ - 如何显示打印预览类别?