在c ++中存储地图中的键的向量,并通过迭代地图访问键的向量

时间:2016-09-25 08:26:16

标签: c++

如何在c ++中为地图中的某个键创建矢量以及如何访问它们? 假设我接受这种格式的数据

UPDATE

这里第一列中的100和56是键,而对于键100,我需要创建一个包含元素的向量6 7 90 8 8 9 对于键56,矢量应为7 8 如何在c ++中实现这一点,同时如何在c ++中访问某个键的向量? 我尝试以这种方式插入向量键,但是无法通过遍历map来访问键的向量。

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

我们如何使用map?

在c ++中完成

1 个答案:

答案 0 :(得分:0)

如果您想使用地图,那么您要做的就是继续添加与该关键字相关联的向量。

以下示例说明了如何执行此操作:

#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);
        }
    }
}

代码中最重要的部分是这一行:

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

std::map::insert函数将返回std::pair,表示插入项的迭代器为对的first,或者如果密钥存在,则表示密钥的现有迭代器已经存在。

然后我们需要做的就是获取该返回值,访问second(这是向量),然后只访问push_back到该向量。

请参阅此live example