I'm currently using g++ on a Cygwin terminal as per my professor's request.
I'm supposed to take in an input file and read it word by word, then place all words inside a vector, sorted alphabetically and with no duplicates.
However, every time I try to manipulate my vector (i.e. - push_back) inside of certain loops, my program just segmentation faults.
Here's a snippet of my code:
void word_count(ifstream& input){
string temp;
vector<string> v;
input >> temp; //set first variable
v.push_back(temp);
while (!input.eof()) { //I'm aware of the limitations while using !eof, this is just the way I am required to loop over a file
input >> temp;
for (vector<string>::iterator i = v.begin(); i != v.end(); i++) { //check entire vector for word
if (*i == temp) { //just break and skip the word if it already exists
break;
}
if (i == v.end() - 1) { //if the word doesn't exist yet
for (vector<string>::iterator k = v.begin(); k != v.end(); k++) { //re-search the vector for the proper place
if (k == v.end() - 1) { //if at the end, just push_back the vector
v.push_back(temp); //Causes segmentation fault
break;
}
if ((*k < temp) && (*(k + 1) > temp)) { //find correct place and insert the word in the vector
v.insert(k, temp); //Also causes segmentation fault if execution even manages to get this far
}
}
}
}
}
}
The first push_back on line 5 is perfectly fine, I can copy and paste that multiple times without error. I can also push_back right after input >> temp (inside of the while loop) without error. However, if I try push_back under the 'k' loop, it segmentation faults. I'm totally stumped.
I've tried looking at the other vector related questions here on StackOverflow, but I don't really understand why I can (or cannot) use push_back in certain places.
Thanks for any help in advance!
Edit 1: I should mention that I tested it in VS 2019. The vector library file popped up, stating a "read-access-violation" exception was thrown. No segmentation faults (Or maybe that's VS's way of telling me a segmentation fault occurred?)
Edit 2: Modifying a vector invalidates iterators. I didn't know that, thanks for the help everyone!
Edit 3: I'm only allowed to use vectors, not sets or other containers. If I could use a set, I totally would.
If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.This is from cppreference frompush_back()method, and probably this is your problemstd::setto save you much work. It's ordered and contains only uniqe elements. It's like it's made for exactly this task.breakonce you've inserted.