0

Most of the answers I'm coming across boil down to in infinite loop, but I've inserted some cout statements for diagnostic purposes and I'm thoroughly convinced this is not the case- it looks like the nested for loop finishes but simply skips over some lines before returning to the top of the outside for loop. The only time something gets pushed back is on the first iteration when the for nested loop is skipped completely. As is, the debugger gives an out of range vector fault, I assume because new unique items aren't being pushed back. Any ideas how to get around this?

Template <class T>
void count_unique(string filename, vector<T> input) {
    vector<T> unique;
    vector<int> count;
    bool found = false;

    ifstream fin;
    fin.open(filename);
    T line;
    while (!fin.eof()) {
        fin >> line;
        input.push_back(line);
    }
    fin.close();

    cout << input.size() << endl;
    for (unsigned int i = 0; i < input.size(); i++) {
        cout << input.at(i) << endl;
    }

    for (unsigned int i = 0; i < input.size(); i++) {
        cout << input.at(i) << endl;
        found = false;

        for (unsigned int j = 0; j < unique.size(); i++) {
            cout << unique.at(j) << "\t=\t" << input.at(i) << " ->" << unique.size() << endl;
            if (input.at(i) == unique.at(j)) {
                count.at(j)++;
                found = true;
                cout << "Incremented" << endl;
            }
            else {
                cout << "None;" << endl;
            }
        }

        cout << "Found=" << found << endl;
        if (!found) {
            unique.push_back(input.at(i));
            count.push_back(1);
            found = false;
            cout << "Pushed back" << endl;
            cout << "#";
            for (unsigned int i = 0; i < unique.size(); i++) {
                cout << unique.at(i) << "\t-\t" << count.at(i) << endl;
            }
            cout << "#" << endl;
        }
    }
    for (unsigned int i = 0; i < unique.size(); i++) {
        cout << "\t" << unique.at(i) << "\t=\t" << count.at(i) << endl;
    }
}
Rai
  • 13
  • 1
  • 2
    Unrelated to your question, but please read [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Some programmer dude Nov 26 '19 at 18:10

1 Answers1

3

Your inner loop incremements the wrong variable. It is actually an infinite loop, since j will never change. This is also why you get the out of range, i will continuously increase, beyond the size of input

//...
for (unsigned int i = 0; i < input.size(); i++) {
    cout << input.at(i) << endl;
    found = false;

    for (unsigned int j = 0; j < unique.size(); j++) { // HERE
ChrisMM
  • 5,195
  • 8
  • 19
  • 34