【问题标题】:how to emplace in map of(string and vector)..?如何在(字符串和向量)的地图中放置..?
【发布时间】:2021-12-11 10:47:50
【问题描述】:

我不确定是否可以在地图容器中包含矢量。

如果是的话,我可以有矢量和矢量的地图吗?

输入

ONE 1 11 111 1111
TWO 22 2 2222
THREE 333 3333 3
map<string, vector<int>> mp;

如何在上面的容器中放置输入?

map<vector<int>, vector<int>> mp;

如果可以实现,您将如何在此处放置元素,以及如何访问这些元素?

【问题讨论】:

  • 使用std::vector&lt;int&gt; 作为std::map 的键类型没有任何意义,尤其是对于您显示的输入。
  • 问:我不确定是否可以在地图容器中包含矢量。答:当然可以!问:我可以有矢量和矢量的地图吗?答:“映射”是一个键::值对。将“向量”作为“键”的目的是什么????你怎么会使用这样的野兽?
  • 您是否有特定的理由怀疑 vector&lt;int&gt; 是否有资格作为地图的键(或值)? std::map 是否有一些您认为可能会失败的要求? (标准容器通常可以容纳任何类型,除非有特定原因不这样做 - 任何此类特定原因都与逻辑一致性有关,而不是有用性。)

标签: c++ c++11 vector stl


【解决方案1】:

您的第一个案例很容易实现,例如:

#include <fstream>
#include <sstream>
#include <map>
#include <vector>
#include <string>
using namespace std;

void loadFile(const string &fileName, map<string, vector<int>> &mp)
{
    ifstream file(fileName.c_str());

    string line;
    while (getline(file, line))
    {
        istringstream iss(line);
        string key;
        if (iss >> key)
        {
            vector<int> &vec = mp[key];
            int value;
            while (iss >> value) {
                vec.push_back(value);
            }
        }
    }
}

int main()
{
    map<string, vector<int>> mp;

    loadFile("input.txt", mp);

    // use mp as needed...

    return 0;
}

【讨论】:

  • 我很确定问题中的“emplace”引用是故意的,它要求std::map::emplace 在这样的容器中需要具有的语法。
  • @SamVarshavchik 这将是上述代码中的 1 行更改。 auto &amp;vec = *(mp.emplace(key, vector&lt;int&gt;{}).first); 但这需要在每次调用 emplace() 时创建一个空的 vector。仅当key 尚不存在时,原始代码才会创建新的vector。要使用emplace() 执行此操作,需要事先调用mp.find() 以事先检查key 的存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2021-08-24
  • 1970-01-01
相关资源
最近更新 更多