katze
katze

Reputation: 13

c++, storing keys and values inside of a map by using for loop

hey guys I'm trying to modify my code and got curious if that can work.

right now I have two for loops that read from two files and store values into two arrays kinda like this:

fstream infile(file_name.c_str());

for(int i=0;i<10;i++){

        infile >> array[i];
}

infile.close();

is there a way to modify it by substituting two arrays with a map? kinda like this:

fstream infile1(file_name1.c_str());
fstream infile2(file_name2.c_str());

map<string,float>my_map;    

for(int i=0;i<10;i++){

        infile1 >>my_map<string> ;

    for(int i=0;i<10;i++){

        infile2 >>my_map<float> ;

Upvotes: 0

Views: 74

Answers (1)

NathanOliver
NathanOliver

Reputation: 180630

If you want to input the data into a map you need to get the values from the file and then add them to the map. Note that a map has unique keys so if a key repeats this will overwrite what was previously in the map. If you do not want that then you would need to use a std::multimap. If you need to use a std::multimap this solution will not work as it has no [] operator.

fstream infile1(file_name1.c_str());
fstream infile2(file_name2.c_str());

map<string,float>my_map;

std::string temp;
float number;

while(infile1 >> temp && infile2 >> number)
    my_map[temp] = number;

Also note that if your strings contain spaces then you need to replace infile1 >> temp with getline(infile1, temp).

Upvotes: 3

Related Questions