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

标签 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;
}

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);

See it live on Coliru here

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

最佳答案

错误是因为元素a 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&)'

只有 map 本身可以对元素重新排序,并且它以任何需要的顺序保持它们以保持其不变性。如果您重新排序它们,您将破坏 map 的内部数据结构。

关于c++ - 为什么我不能 std::partition 这个 std::unordered_map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42433874/

相关文章:

c++ - 使进程在大内存分配时崩溃

c++ - 无法为指针 vector 编译比较函数

c++ - 避免原始循环并改用 std::algorithm

c++ - 为什么通过引用返回 vector 比通过 move 返回快得多?

c++ - 从使用另一个共享库的源文件构建和使用共享库。 (R里面)

c++ - 使用字符串替换函数用初始化变量替换字符串的一部分?

c++ - 从类成员生成容器

c++ - 检查 vector 中的一组值

C++,copy_if 与 vector <class>

c++ - Winsock 接收缓冲区错误