这不会构建,我不明白编译错误。
#include <unordered_map>
#include <algorithm>
int main()
{
std::unordered_map<int, size_t> occurences = { { 10, 2 }, { 20, 5 }, { 30, 0 }, { 40, 5 }, { 50, 0 }, { 100, 9 } };
auto newEnd = std::partition(occurences.begin(), occurences.end(), [](const std::pair<int, size_t> &p)
{
return p.second == 0;
});
return 0;
}
g++ 提示如下。 VS2013 更加神秘。
/usr/local/include/c++/6.3.0/bits/stl_pair.h: In instantiation of 'void std::pair<_T1, _T2>::swap(std::pair<_T1, _T2>&) [with _T1 = const int; _T2 = long unsigned int]': /usr/local/include/c++/6.3.0/bits/stl_pair.h:473:7: required from 'void std::swap(std::pair<_T1, _T2>&, std::pair<_T1, _T2>&) [with _T1 = const int; _T2 = long unsigned int]' /usr/local/include/c++/6.3.0/bits/stl_algobase.h:148:11: required from 'void std::iter_swap(_ForwardIterator1, _ForwardIterator2) [with _ForwardIterator1 = std::__detail::_Node_iterator, false, false>; _ForwardIterator2 = std::__detail::_Node_iterator, false, false>]' /usr/local/include/c++/6.3.0/bits/stl_algo.h:1500:20: required from '_ForwardIterator std::__partition(_ForwardIterator, _ForwardIterator, _Predicate, std::forward_iterator_tag) [with _ForwardIterator = std::__detail::_Node_iterator, false, false>; _Predicate = main()::&)>]' /usr/local/include/c++/6.3.0/bits/stl_algo.h:4524:30: required from '_BIter std::partition(_BIter, _BIter, _Predicate) [with _BIter = std::__detail::_Node_iterator, false, false>; _Predicate = main()::&)>]' main.cpp:12:4: required from here /usr/local/include/c++/6.3.0/bits/stl_pair.h:416:6: error: no matching function for call to 'swap(const int&, const int&)' swap(first, __p.first);
据我所知,这张 map 符合 cppreference.com 上列出的 std::partition 类型要求。所以我很难过。我的问题是为什么它不构建?
最佳答案
错误是因为元素a map
和 unordered_map
是std::pair<const Key, value>
不 std::pair<Key, Value>
, 所以你不能使用像 std::partition
这样的算法重新排序它们因为const Key
无法修改:
error: no matching function for call to 'swap(const int&, const int&)'
只有 map 本身可以对元素重新排序,并且它以任何需要的顺序保持它们以保持其不变性。如果您重新排序它们,您将破坏 map 的内部数据结构。
关于c++ - 为什么我不能 std::partition 这个 std::unordered_map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42433874/