0

I have a file that looks like this:

a
a
a
a
b
b
c
d
d
d

I'm using fstream and sstream to read it, and what i want to achieve is to read through it counting how many times a single element is repeated, so i can add a node to a BST with the repetition count as its key.

I'm hoping to achieve something like this:

myBST.insert("a", 4);
myBST.insert("b", 2);
myBST.insert("c", 1);
myBST.insert("d", 3);

I've tried creating a while loop with a new sstream where the main loop finds an element, counting how many times the value being read by the new sstream is the same as the original sstream, but it doesn't seem to be working:

    if (!datos.is_open())
    {
        cout << "failed to open";
    }

    string line;
    
    while (getline(datos, line))
    {
        stringstream ss(line);

        int count = 0;

        string line2 = line;
        stringstream ss2(line2);
        while (line2 == line)
        {
            stringstream ss2(line2);
            count++;
        }       
        
    }
    return 0;

Any help is appreciated :)

cheveuxdelin
  • 127
  • 2
  • 9
  • 4
    You could use e.g. [`std::unordered_map`](https://en.cppreference.com/w/cpp/container/unordered_map) to keep track of "repetitions". Use the input from the file as the key and the count as the data. Then you can just do `map[line]++`. And afterwards iterate over the map and you have the strings and the repetitions. – Some programmer dude Oct 26 '20 at 23:34
  • It could work but i also have to keep track of when does it stop repeating – cheveuxdelin Oct 27 '20 at 03:22
  • _i also have to keep track of when does it stop repeating_ That's exactly what `map[line]++` would achieve. Whenever a non-repeated `line` occurs the `map[line]` will insert a new `std::pair(line, 0);` which is then incremented the first time. Please, read again how the [std::unordered_map::operator[\]](https://en.cppreference.com/w/cpp/container/unordered_map/operator_at) works: _Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist._ – Scheff's Cat Oct 27 '20 at 06:54
  • _i also have to keep track of when does it stop repeating_ Or does it mean you want to do something in this case (e.g. store or print the current line number)? That's as easy as well: `if (++map[line] == 1) { /* non-repeated line occurred */ }`. – Scheff's Cat Oct 27 '20 at 07:02
  • If you want to keep the sorted order, I would prefer `std::map` over `std::unordered_map`: [**Demo on coliru**](http://coliru.stacked-crooked.com/a/1e9880da684bcaa5) – Scheff's Cat Oct 27 '20 at 07:18

0 Answers0