Search code examples
c++vectorfile-read

Extract data from file into vectors but avoid duplicates


I want to read data in files that are formatted like:

Point1, [3, 4]

I'm using delimiters '[' ']' and ',' and replace them with ' ' (empty space). My code now is fine and working. But the problem is, if Point1, [3, 4] appeared once, I want it to be unique and not to appear again if the same data in the text file exist.

Here is what I have:

string line, name;
char filename[50];
int x,y;

cout << "Please enter filename : ";
cin >> filename;

ifstream myfile(filename);
if (myfile.is_open()) {
    while ( myfile.good() ) {
        getline(myfile, line);

        for (unsigned int i = 0; i < line.size(); ++i) {
            if (line[i] == '[' || line[i] == ']' || line[i] == ',') {
                line[i] = ' ';
            }
            istringstream in(line);
            in >> name >> x >> y;                                  
        }
        cout <<name <<endl;

        if (name=="Point") {
            p.push_back(Point(x,y));         
        }                          
        count++;
    }    
    myfile.close();
    cout << count;
}
else cout<< "Unable to open file";

How do i do this? I tried adding this after if(name=="Point")

for (int j=0; j<p.size(); j++) {
    if(p.getX != x && p.getY) != y) {
        p.push_back(Point(x,y))
    }
}

...but this is not working properly as data was not stored into the vector.

Anyone can help?


Solution

  • Instead of storing your data into vectors you can store it into sets. A set contains only unique values, so you don't have to check the uniqueness of your Points, the set will manage that.

    Instead of defining vector<Point>, you have to define set<Point>, and instead of using p.push_back to add points into your vector, you have to use p.insert if it is a set.

    You can check the set documentation here.