How can I use an array as map value?

后端 未结 8 1451
太阳男子
太阳男子 2020-12-01 08:04

I\'m trying to create a map, where the key is an int, and the value is an array as follows:

int red[3]   = {1,0,0};
int green[3] = {0,1,0};
int b         


        
相关标签:
8条回答
  • 2020-12-01 08:46

    Arrays cannot be the stored data in a standard container( std::pair)

    0 讨论(0)
  • 2020-12-01 08:46

    I'd like to expand on the third item of Brian R. Bondy's answer: Since C++11 the class template std::tuple is available. So you no longer need Boost to work with tuples.

    A tuple is a collection of fixed size that can hold multiple elements. Compared to e.g. std::vector it has the advantage that it can store heterogeneous types. For example, if you want to store the name of the color together with its RGB values, you can add a fourth element of type std::string for the color name to the tuple. But for your specific use case, the code could be written as follows:

    int main() {
        using col_t = std::tuple<int, int, int>;
        col_t red   = { 1, 0, 0 };
        col_t green = { 0, 1, 0 };
        col_t blue  = { 0, 0, 1 };
    
        std::map<int, col_t> colours;
    
        colours.emplace(GLUT_LEFT_BUTTON, red);
        colours.emplace(GLUT_MIDDLE_BUTTON, blue);
        colours.emplace(GLUT_RIGHT_BUTTON, green);
    
        for (auto const &kv : colours)
            std::cout << kv.first << " => { " << std::get<0>(kv.second) << ", "
                                              << std::get<1>(kv.second) << ", "
                                              << std::get<2>(kv.second) << " }" << std::endl;
        return 0;
    }
    

    Output:

    0 => { 1, 0, 0 }
    1 => { 0, 0, 1 }
    2 => { 0, 1, 0 }

    Note: Working with tuples became easier with C++17, 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] : colours) {
        auto [r, g, b] = v;
        std::cout << k << " => { " << r << ", " << g << ", " << b << " }" << std::endl;
    }
    

    Code on Coliru

    0 讨论(0)
提交回复
热议问题