Summary:
It seems like just calling clear()
on a vector is not enough to clear it.
vector_full_of_stuff.clear();
I had to call clear()
and then shrink_to_fit()
to completely delete all data inside of it.
vector_full_of_stuff.clear();
// AND THEN
vector_full_of_stuff.shrink_to_fit();
What gives? This became a problem because when I would call data()
on a vector, it would include stuff that I thought should have been cleared when I called clear()
earlier in the code.
Additional Details:
I am doing an computer networking assignment where I have to parse a PASV command result into an IP and Port Number. While parsing a fictitious PASV command result separated by commas, I noticed that if I parse a three digit followed by a two digit I get that third digit from the previous parse when calling data()
even though I shouldn't (?) because I called clear()
before it.
ex.
PASV Command Result = 209,202,252,54,19,15
The "2" from "252" carries over into "19" when parsing.
Code:
// this one actually deletes data
void splitString(string str, char delimiter, vector<string> * out) {
vector<char> word_buffer;
for (int i = 0; i < str.length(); ++i) {
if (str[i] == delimiter) {
out->push_back(word_buffer.data());
word_buffer.clear();
word_buffer.shrink_to_fit();
} else {
word_buffer.push_back(str[i]);
}
}
out->push_back(word_buffer.data());
word_buffer.clear();
}
//
// this one doesn't
// the only thing that's different about this one
// is that its missing shrink_to_fit()
void splitString(string str, char delimiter, vector<string> * out) {
vector<char> word_buffer;
for (int i = 0; i < str.length(); ++i) {
if (str[i] == delimiter) {
out->push_back(word_buffer.data());
word_buffer.clear();
// word_buffer.shrink_to_fit(); // need this to delete data
} else {
word_buffer.push_back(str[i]);
}
}
out->push_back(word_buffer.data());
word_buffer.clear();
}
//
// main driver code
int main() {
vector<string> user_input_tokens;
string port = "209,202,252,54,19,15";
splitString(port, ',', &user_input_tokens);
for (string str : user_input_tokens) {
cout << str << ".";
}
}
//
Expected Output:
209.202.252.54.19.15.
Actual Output:
209.202.252.542.192.152.