I have python code that I am trying to convert to C++ equivalent.
dict1 = {i:(val1,val2,val3)}
dict_sorted = sorted(dict1.items(), key=lambda kv: kv[1][2])
This will sort dictionary dict1
by val3
and stored in dict_sorted
(which is not a dictionary).
In c++, I have std::unordered_map<int, std::vector<double>> dict1
, or map
similar to above. Vector will have val1,val2,val3
. How can I sort this unordered map using val3
?
As I noted in the comments , the Python code is making a sorted list
of two- tuple
s, sorting based on the third element of the second element in each tuple
(the result is not a dict
). For equivalent C++ code, you're replacing dict
with std::unordered_map
, list
with std::vector
, and the two- tuple
with std::pair
; to precisely match Python's sorted
results, you'd want to use std::stable_sort
for the sorting.
So something like (where dict1
is your unordered_map
):
using kv_pair = std::pair<int, std::vector<double>>;
std::vector<kv_pair> dict_sorted;
dict_sorted.reserve(dict1.size());
for (const auto& kv : dict1) {
dict_sorted.emplace_back(kv.first, kv.second);
}
std::stable_sort(std::begin(dict_sorted), std::end(dict_sorted),
[](const kv_pair& a, const kv_pair& b) { return a.second[2] < b.second[2]; });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.