Home > Software engineering >  how to emplace in map of(string and vector)..?
how to emplace in map of(string and vector)..?

Time:10-28

I'm not sure if it is possible to have a vector inside of a map container.

If yes, can I have the map with vector and vector?

INPUT

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

How to emplace the input in the above container?

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

If this is possible to implement, how will you emplace elements here, and how can you access those elements?

CodePudding user response:

Your first case is fairly easy to implement, eg:

#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;
}
  • Related