如何从std::map中选取前k个元素

问题描述 投票:0回答:1

我有一个

std::map
,其中
uint32_t
作为键类型和自定义值类型。我想根据值类型的成员从该映射中挑选出前 k 键值对。为此,我首先将
std::map
的所有元素复制到
std::vector
,然后对向量进行排序。最后,我删除了向量中索引大于 k 的所有元素。这是我的代码:

#include <algorithm>                                                                                                                                                                                           
#include <cstdint>
#include <iostream>
#include <map>
#include <vector>

struct Values
{
        uint32_t a = 0;
        uint32_t b = 0;

        Values(uint32_t x, uint32_t y): a(x), b(y) {}
};

template <typename MapType>
auto print_top_k(std::size_t k, MapType&& map)
{
        std::vector<typename MapType::value_type> v;
        v.reserve(map.size());

        std::transform(map.begin(), map.end(), std::back_inserter(v), [](const auto& kv) { return kv; });
        std::sort(v.begin(), v.end(), [](const auto& lhs, const auto& rhs){ return lhs.second.a > rhs.second.b; }); 
        v.erase(v.begin() + k, v.end());

        for(const auto& kv: v)
                std::cout << kv.first << " -> (" << kv.second.a << ", " << kv.second.b << ")\n";
}

int main()
{
        std::map<uint32_t, Values> data;
        for(uint32_t i = 0; i < 100; i++)
                data.emplace(std::piecewise_construct, std::forward_as_tuple(i), std::forward_as_tuple(2*i, 3*i));

        print_top_k(10, std::move(data));

        return 0;
}

我正在使用

GCC
来编译这个:

gcc -std=c++23 -Ofast -Wall -Wextra -Wpedantic -Wconversion -Werror main.cpp

这是编译器资源管理器的链接。

但是,此代码无法编译,因为我在

std::sort
处收到错误。

  1. 为什么我在这段代码中遇到编译错误?
  2. 这些错误是什么意思?有人可以将它们从海湾合作委员会语言翻译成英语吗?
  3. 如何修复这些错误?
stdvector stdmap libstdc++ c++23
1个回答
0
投票
std::vector<typename MapType::value_type> v;

map 的

value_type
std::pair<const Key, T>
const
元素禁用
std::sort
需要移动元素的移动赋值运算符。

你需要使用

std::vector<std::pair<typename MapType::key_type, typename MapType::mapped_type>> v;

神箭链接


至于翻译,你得到的错误是:

错误:使用已删除的函数 'std::pair<_T1, _T2>& std::pair<_T1, _T2>::operator=(const std::pair<_T1, _T2>&) [with _T1 = const unsigned int; _T2 = 值]

翻译过来就是,

std::pair<const unsigned int, Values>
已删除
operator=

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.