如果我们有
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()));
对于方法二,你可以这样做:
std::set<int> a{ 1, 2, 3, 4, 5};
std::vector<std::unordered_set<int>> b(1);
b[0].insert(a.begin(), a.end());
或者作为替代:
std::set<int> a{ 1, 2, 3, 4, 5};
std::vector<std::unordered_set<int>> b;
b.push_back({a.begin(), a.end()});
或者作为 @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());
关于C++ 我们如何在 std::vector<std::unordered_set> 中插入 std::set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24316568/