简体   繁体   中英

storing vector for a key in map in c++ and accessing the vector for key by iterating through map

How do create a vector for a certain key in map in c++ and how to access them ? suppose i accept data in this format

   100 6 7
   56 7 8
   100 90 8
   100 8 9

Here 100 and 56 in first column are keys and for key 100 i need to create a vector containing elements 6 7 90 8 8 9 and for key 56 ,vector should be 7 8 .How can we do this in c++ and at same time how to access the vector for a certain key in c++? I tried to inset vector a key this way but could not access the vector for key by iterating through map .

 int k;
cin>>k;
for(int i=1;i<=k;i++){
    int r,c1,c2;
    cin>>r>>c1>>c2;
     mymap[r].push_back(c1);
     mymap[r].push_back(c2);

}

HOW can we do it in c++ using map ?

If you want to use a map, then what you want to do is keep adding to the vector that's associated with the key.

The following example shows how to do this:

#include <map>
#include <vector>
#include <string>
#include <sstream>

typedef std::map<int, std::vector<int>> MapV;

using namespace std;

int main()
{
    MapV mymap;
    string line;

    // get one line of data
    while (getline(cin, line))
    {
        // use a string stream to parse the data
        istringstream strm(line);
        int key, data;

        // first value is the key
        strm >> key;

        // all other values are the data
        while (strm >> data)
        {
            // the magic is here.
            auto pr = mv.insert(make_pair(key, std::vector<int>()));

            // add item to the vector
            pr.first->second.push_back(data);
        }
    }
}

The most important part of the code is this line:

    auto pr = mv.insert(make_pair(key, std::vector<int>()));

The std::map::insert function will return a std::pair , denoting the iterator to the inserted item as the first of the pair, or if the key exists, the existing iterator to the key that already exists.

Then all we need to do is to take that return value, access the second (which is the vector), and merely push_back onto that vector.

See this live example

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM