Remove() and replace() elements in vector - C++ STL Algorithm

C++ examples for STL Algorithm:remove

Description

Remove() and replace() elements in vector

Demo Code

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template<class InIter>
void show_range(const char *msg, InIter start, InIter end);
int main()/*www.ja va  2  s.c om*/
{
   vector<char> v;
   vector<char>::iterator itr, itr_end;
   // Create a vector that contains A B C D E A B C D E.
   for(int i=0; i<5; i++) {
      v.push_back('A'+i);
   }
   for(int i=0; i<5; i++) {
      v.push_back('A'+i);
   }
   show_range("Original contents of v:\n", v.begin(), v.end());
   cout << endl;
   // Remove all A's.
   itr_end = remove(v.begin(), v.end(), 'A');
   show_range("v after removing all A's:\n", v.begin(), itr_end);
   cout << endl;
   // Replace B's with X's
   replace(v.begin(), v.end(), 'B', 'X');
   show_range("v after replacing B with X:\n", v.begin(), itr_end);
   cout << endl;
   return 0;
}
// Show a range of elements from a vector<char>.
template<class InIter>
void show_range(const char *msg, InIter start, InIter end) {
   InIter itr;
   cout << msg;
   for(itr = start; itr != end; ++itr)
      cout << *itr << " ";
   cout << endl;
}

Result


Related Tutorials