Searching and Inserting in a map with 3 elements in C++

后端 未结 3 1282
情话喂你
情话喂你 2021-01-02 20:47

I need to have a map like this :

typedef std::map Maptype ;

What is the syntax to insert and searching elements of

相关标签:
3条回答
  • 2021-01-02 21:10

    A map can only map one key type to one data type. If the data contains 2 elements, use a struct or a std::pair.

    typedef std::map<int, std::pair<float, char> > Maptype;
    ...
    Maptype m;
    m[123] = std::make_pair(0.5f, 'c');
    ...
    std::pair<float, char> val = m[245];
    std::cout << "float: " << val.first << ", char: " << val.second << std::endl;
    
    0 讨论(0)
  • 2021-01-02 21:20

    Use either

    std::map<std::pair<int, float>, char>
    

    or

    std::map<int, std::pair<float, char> >
    

    whichever is correct.

    0 讨论(0)
  • 2021-01-02 21:22

    You cannot have three elements. The STL map stores a key-value pair. You need to decide on what you are going to use as a key. Once done, you can probably nest the other two in a separate map and use it as:

    typedef std::map<int, std::map<float, char> > MapType;
    

    In order to insert in a map, use the operator[] or the insert member function. You can search for using the find member function.

    MapType m;
    // insert
    m.insert(std::make_pair(4, std::make_pair(3.2, 'a')));
    m[ -4 ] = make_pair(2.4, 'z');
    // fnd
    MapType::iterator i = m.find(-4);
    if (i != m.end()) { // item exists ...
    }
    

    Additionally you can look at Boost.Tuple.

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