Home > Mobile >  c creating a map (with vectors) from a text file
c creating a map (with vectors) from a text file

Time:09-30

I have a text file containing a list of variable names:

name1
name2
name3
...

I want to read this in and create a map where the keys are strings of these names, and the values are vectors of floats with these names. My goal is to be able to loop through the map and perform operations on the vectors in bulk, such as clearing them all.

I can read the names as strings easily, and add them to an array or vector, but am not sure how to create vectors with the list of names.

CodePudding user response:

Have a look at std::map or (std::unordered_map), eg:

#include <map>
#include <fstream>
#include <string>
#include <vector>

std::map<std::string, std::vector<float>> mymap;

std::ifstream in("names.txt");
std::string name;

while (std::getline(in, name))
{
    if (mymap.find(name) == mymap.end())
        mymap.insert(std::make_pair(name, std::vector<float>()));

    // or simply let operator[] construct the pair if it doesn't already exist:
    // mymap[name];
}

Then, you can do things like this:

mymap["somename"].push_back(someValue);
for(auto &elem : mymap)
{
    // do something with elem.first (name) and elem.second (vector) as needed...
    elem.second.clear();
}

CodePudding user response:

Something like this should work:

#include <fstream>
#include <map>
#include <vector>
#include <string>

std::map<std::string, std::vector<float>> names;
std::ifstream file(FILENAME);
if (file.is_open()) {
    std::string line;
    while (std::getline(file, line))
      names[line];
    
    file.close();
}
...
names["name1"].emplace_back(4);
...
for(const auto &name:names) {
    cout << name.first;
    for(const auto &value:name.second)
        cout << value << endl;
}

Or use unordered_map which can be faster (uses hash table instead of BST) if you don't need your elements sorted.

  •  Tags:  
  • c
  • Related