簡體   English   中英

如何通過矢量值訂購 map c++

[英]how to order map by vector value c++

std::map<int, std::vector<int>> tmp_map = { { 1, [10,5,4] }, { 2, [5,5,1] },
        { 3, [2,4,3] }, { 4, [9,7,8] } };

我想按向量值的第三個值訂購這個 map。 所以結果會是這樣的:

{ { 2, [5,5,1] },{ 3, [2,4,3] },{ 1, [10,5,4] },{ 4, [9,7,8] } }

標准方法。 . .

  • 將 map 復制到矢量
  • 使用自定義比較器對向量進行排序
#include <iostream>
#include <map>
#include <vector>
#include <utility>
#include <algorithm>

int main() {
    std::map<int, std::vector<int>> tmp_map = { { 1,{10,5,4} }, { 2,{5,5,1} },
        { 3,{2,4,3} }, { 4,{9,7,8} } };

    // For easier and shorter writing
    using DataType = std::pair<int, std::vector<int>>;

    // Create Vector with Elements from Map
    std::vector<DataType> data(tmp_map.begin(), tmp_map.end());

    // Sort data
    std::sort(data.begin(), data.end(), [](const DataType& d1, const DataType& d2) { return d1.second[2] < d2.second[2]; });

    // show result
    for (const auto& [key, value] : data) {
        std::cout << key << "  -->  ";
        for (const int i : value) std::cout << i << " ";
        std::cout << "\n";
    }
    return 0;
}

您是map已按其鍵值排序,因此您無法就地重新排序。 您應該做的是將其復制到向量中,然后使用如下自定義運算符對其進行排序:

#include <map>
#include <vector>
#include <algorithm>

int main()
{
    std::map<int, std::vector<int>> tmp_map = { { 1, {10,5,4} }, { 2, {5,5,1} },
        { 3, {2,4,3} }, { 4, {9,7,8} } };

    //! Copy the map
    using P = std::pair<int, std::vector<int>>;
    std::vector<P> copy(tmp_map.begin(), tmp_map.end());

    //! Sort it the way you want (here I'm sorting on based on the second element
    //! of the array.
    std::sort(copy.begin(), copy.end(), [](const P& a, const P& b)
    {
        return a.second[2] < b.second[2];
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM