-1

As the title explains, I am for some reason getting different results using std::remove on vectors of different types, namely of strings and ints. For the vector of ints, the function is working as expected and not actually physically removing the element. However, it does physically remove the element for the vector of strings and I can't seem to figure out why (feel like it's something small I'm overlooking). If anyone can explain why this is happening that would be really great. I've posted the code and the output below. Thanks!

//includes
using namespace std;

template <class T>
void printer(T value) {
    cout << value << ", "
}

int main() {
    string myvalues[] = { "yyy","Yyy", "yYy","yyY","ZZZ","zZZ", "ZzZ", "ZZz" };
    int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
    vector<string> v1(myvalues, myvalues + 8);
    vector<int> v2(nums, nums + 8);
    sort(v1.begin(), v1.end());
    remove(v2.begin(), v2.end(), 7);
    remove(v1.begin(), v1.end(), "yyy");
    for_each(v1.begin(), v1.end(), printer<string>);
    cout << endl;
    for_each(v2.begin(), v2.end(), printer<int>);

    return 0;
}

Output:

Yyy, ZZZ, ZZz, ZzZ, yYy, yyY, zZZ, ,

1, 2, 3, 4, 5, 6, 8, 8,

As you can see the element "yyy" was actually removed leaving the last element empty, whereas the element "7" was logically removed leaving the last element unchanged.

4
  • 1
    Post compilable code.
    – user2100815
    May 24, 2017 at 17:37
  • 2
    Shrug. Once you've removed an element your sequence is smaller, and you shouldn't be looking beyond its end. May 24, 2017 at 17:38
  • Did you notice the double comma in the output?
    – rustyx
    May 24, 2017 at 17:45
  • Really didn't find this an EXACT duplicate but okay. Was just confused that the elements at the end of the string vector were altered (changed to empty strings) after the removal while they remain unchanged in vectors of ints, doubles, etc.
    – Ndesai94
    May 24, 2017 at 19:06

1 Answer 1

1

From the reference of std::remove:

The relative order of the elements not removed is preserved, while the elements between the returned iterator and last are left in a valid but unspecified state.

Hence, in both cases the function is behaving "correctly".

1
  • Not sure why the difference between int and string, though. Probably the implementation for strings is using some sort of swap with empty strings, while for int's is just assigning the next values? May 24, 2017 at 17:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.