gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:40:28 26 4
gpt4 key购买 nike

如果我们有

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com