为什么我不能std :: partition这个std :: unordered_map?

acr*_*075 0 c++ stl-algorithm

这不构建,我不理解编译错误.

#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;
}
Run Code Online (Sandbox Code Playgroud)

g ++抱怨如下.VS2013更加神秘.

/usr/local/include/c++/6.3.0/bits/stl_pair.h:实例化'void std :: pair <_T1,_T2> :: swap(std :: pair <_T1,_T2>&)[与_T1 = const int; _T2 = long unsigned int]':/ usr/local/include/c + +/6.3.0 /bits/stl_pair.h:473:7:从'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:'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:需要'_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:需要'_BIter std :: partition(_BIter,_BIter,_Predicate) [with _BIter = std :: __ detail :: _ Node_iterator,false,false>; _Predicate = main()::&)>]'main.cpp:12:4:从这里要求/usr/local/include/c++/6.3.0/bits/stl_pair.h:416:6:错误:没有匹配函数调用'swap(const int&,const int&)'swap(first,__ p.first);

在这里现场观看Coliru

据我所知,这张地图符合cppreference.com上列出的std :: partition类型要求所以我很难过.我的问题是它为什么不构建?

Jon*_*ely 6

这个错误是因为的元素mapunordered_mapstd::pair<const Key, value> 不是 std::pair<Key, Value>,所以你不能再命令他们使用类似的算法std::partition,因为const Key不能被修改:

error: no matching function for call to 'swap(const int&, const int&)'
Run Code Online (Sandbox Code Playgroud)

只有地图本身可以重新排序元素,并且它以任何顺序保持它们以保持其不变量.如果您重新订购它们,您将破坏地图的内部数据结构.


izo*_*ica 5

std::partition对提供的容器中的元素重新排序,但是您不能对 a 的元素重新排序std::map- 它的元素具有预定义的固定顺序。该标准保证在迭代地图元素时,您将始终按递增顺序迭代它们。

正如您unordered_map在标题中提到的,我还将提到,与map它不同的是,它不保证其元素的顺序,但也无法对其元素进行重新排序。毕竟unordered_map无序的,所以它永远不会保证您迭代其元素的顺序。