简体   繁体   English

在 C++ 中的 map 中存储键的向量并通过迭代 map 访问键的向量

[英]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 ?如何在 C++ 中为 map 中的某个键创建向量以及如何访问它们? 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++?这里第一列中的 100 和 56 是键,对于键 100,我需要创建一个包含元素 6 7 90 8 8 9 的向量,对于键 56,向量应该是 7 8 。我们如何在 C++ 中做到这一点,同时如何在 C++ 中访问某个键的向量? I tried to inset vector a key this way but could not access the vector for key by iterating through map .我试图以这种方式插入向量一个键,但无法通过遍历 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 ?我们如何使用 map 在 C++ 中做到这一点?

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. std::map::insert函数将返回一个std::pair ,将插入项的迭代器表示为该对的first ,或者如果键存在,则表示已经存在的键的现有迭代器。

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.然后我们需要做的就是获取该返回值,访问second (即向量),然后仅push_back到该向量上。

See this live example看到这个现场例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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