What is the best way to use two keys with a std::map?

后端 未结 9 1827
你的背包
你的背包 2021-01-30 03:54

I have a std::map that I\'m using to store values for x and y coordinates. My data is very sparse, so I don\'t want to use arrays or vectors, which would result in

9条回答
  •  醉酒成梦
    2021-01-30 04:35

    I think for your use case, std::pair, as suggested in David Norman's answer, is the best solution. However, since C++11 you can also use std::tuple. Tuples are useful if you have more than two keys, for example if you have 3D coordinates (i.e. x, y, and z). Then you don't have to nest pairs or define a comparator for a struct. But for your specific use case, the code could be written as follows:

    int main() {
        using tup_t = std::tuple;
        std::map m;
    
        m[std::make_tuple(78, 26)] = 476;
        tup_t t = { 12, 45 }; m[t] = 102;
    
        for (auto const &kv : m)
            std::cout << "{ " << std::get<0>(kv.first) << ", "
                              << std::get<1>(kv.first) << " } => " << kv.second << std::endl;
        return 0;
    }
    

    Output:

    { 12, 45 } => 102
    { 78, 26 } => 476

    Note: Since C++17 working with tuples has become easier, espcially if you want to access multiple elements simultaneously. For example, if you use structured binding, you can print the tuple as follows:

    for (auto const &[k, v] : m) {
        auto [x, y] = k;
        std::cout << "{ " << x << ", " << y << " } => " << v << std::endl;
    }
    

    Code on Coliru

提交回复
热议问题