现在的位置: 首页 > 综合 > 正文

简单的程序诠释C++ STL算法系列之十九:replace

2013年06月04日 ⁄ 综合 ⁄ 共 1326字 ⁄ 字号 评论关闭

    替换算法将指定元素值替换为新值,使用原型如下,将迭代器[first,last)中值为old_value的元素全部替换为new_value值。

    函数原型:

template < class ForwardIterator, class T >
  void replace ( ForwardIterator first, ForwardIterator last,
                 const T& old_value, const T& new_value );

     参数说明:

first, last
指出要替换的迭代器区间[first,last)
old_value
将要被替换的元素值
new_value
将要替换旧值的新值

     程序示例:

/*******************************************************************  
 * Copyright (C) Jerry Jiang  
 *                 
 * File Name   : replace .cpp  
 * Author      : Jerry Jiang  
 * Create Time : 2012-4-29 22:22:18  
 * Mail        : jbiaojerry@gmail.com  
 * Blog        : http://blog.csdn.net/jerryjbiao   
 *                 
 * Description : 简单的程序诠释C++ STL算法系列之十九                    
 *               变易算法 : 替代 replace 
 *                 
 ******************************************************************/    
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main () {
  int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };
  vector<int> myvector (myints, myints+8);            // 10 20 30 30 20 10 10 20

  replace (myvector.begin(), myvector.end(), 20, 99); // 10 99 30 30 99 10 10 99

  cout << "myvector contains:";
  for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    cout << " " << *it;

  cout << endl;
 
  return 0;
}

*******************************************************************************************************************************

C++经典书目索引及资源下载:http://blog.csdn.net/jerryjbiao/article/details/7358796

********************************************************************************************************************************

抱歉!评论已关闭.