C++ replace replace_if replace_copy replace_copy_if

#include <iostream>
#include <list>
#include <algorithm>
#include <iterator>
#include <functional>

using namespace std;

int main()
{
  list<int> list1;
  list<int> list2;

  for (int k=0;k<10;k++)
  {
    list1.push_back(k);
  }

  list<int>::iterator list_iter1;
  for (list_iter1 = list1.begin(); list_iter1 != list1.end(); ++ list_iter1)
  {
    cout << *list_iter1 << " ";
  }
  cout << endl;
  cout << "-----------------------------------------------------" << endl;

  replace(list1.begin(), list1.end(), 6, 42);
  for (list_iter1 = list1.begin(); list_iter1 != list1.end(); ++list_iter1)
  {
    cout << *list_iter1 << " ";
  }
  cout << endl;
  cout << "-----------------------------------------------------" << endl;

  replace_if(list1.begin(), list1.end(), bind2nd(less<int>(), 5), 11);
  for (list_iter1 = list1.begin(); list_iter1 != list1.end(); ++list_iter1)
  {
    cout << *list_iter1 << " ";
  }
  cout << endl;
  cout << "-----------------------------------------------------" << endl;

  for (int k=0;k<7;k++)
  {
    list2.push_back(k);
  }

  for (int k = 4; k<10; k++)
  {
    list2.push_back(k);
  }

  list<int>::iterator list_iter2;
  for (list_iter2 = list2.begin(); list_iter2 != list2.end(); ++list_iter2)
  {
    cout << *list_iter2 << " ";
  }
  cout << endl;
  cout << "-----------------------------------------------------" << endl;

  replace_copy(list2.begin(), list2.end(), ostream_iterator<int>(cout, " "), 5, 55);
  cout << endl;
  cout << "-----------------------------------------------------" << endl;

  replace_copy_if(list2.begin(), list2.end(), ostream_iterator<int>(cout, " "), bind2nd(less<int>(), 5), 46);
  cout << endl;
  cout << "-----------------------------------------------------" << endl;

 


  system("pause");
  return 0;
}

===============================================

0 1 2 3 4 5 6 7 8 9
-----------------------------------------------------
0 1 2 3 4 5 42 7 8 9
-----------------------------------------------------
11 11 11 11 11 5 42 7 8 9
-----------------------------------------------------
0 1 2 3 4 5 6 4 5 6 7 8 9
-----------------------------------------------------
0 1 2 3 4 55 6 4 55 6 7 8 9
-----------------------------------------------------
46 46 46 46 46 5 6 46 5 6 7 8 9
-----------------------------------------------------
请按任意键继续. . .

posted @ 2019-06-12 16:37  西北逍遥  阅读(337)  评论(0编辑  收藏  举报