Hajer Hraiech Sakly
Hajer Hraiech Sakly

Reputation: 15

C++ use map to compare each word in a string

I need to compare all the lines in a file starting from the 3rd word (which is "TO") and if two lines are identical i have to merge them.

Example; this is my text file :

STATE a TO a x b b OUT 0 x 0 1
STATE b TO a x b b OUT 0 x 0 1
STATE c TO d b b b OUT 0 1 1 0 
STATE d TO c b b b OUT 0 1 1 0 
STATE e TO d b b b OUT 0 1 1 0 

this is the output that i need :

STATE ab TO a x b b OUT 0 x 0 1
STATE ce TO d b b b OUT 0 1 1 0 
STATE d TO c b b b OUT 0 1 1 0 

this is my code, it does delete second line if 2 are identical but I couldn't figure out how to merge the states (a, b ,c..) I think i have to use 2D map and i don't know how to use it under these conditions

#include <iostream>
#include <fstream>
#include <iterator>
#include <sstream>
#include <string>
#include <map>

using namespace std;

int main() {
    map<std::string, std::string> _map;
    map<string, string>::iterator it;
    string str1, str2;
    ifstream reader("Hajer.txt"); // my file
    while (getline(reader, str2)) {
        str1 = str2.substr(0, 8); // I compare them beginning from "TO"
        str2.erase(0, 8);
        _map[str2] = str1;        
    }
    reader.close();
    ofstream writer("New_Hajer.txt"); // the result
    for (it = _map.begin(); it != _map.end(); ++it)        
        writer << it->second << it->first << '\n';
    writer.close();
    return 0;
}

Thank you for your answers.

Upvotes: 0

Views: 92

Answers (1)

acraig5075
acraig5075

Reputation: 10756

What you're doing is that each time you find a match you are replacing the previous map value with the new value.

_map[str2] = str1;

Instead, if _map[str2] already contains a value, then you want to append to the existing value.

auto found = _map.find(str2);

if (found == _map.end())
    _map[str2] = str1; // first occurrence
else
    found->second += str1.substr(6); // append subsequent occurrences

Upvotes: 1

Related Questions