您的位置:首页 > 编程语言 > C语言/C++

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

2012-04-29 22:14 302 查看
替换算法将指定元素值替换为新值,使用原型如下,将迭代器[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++经典书目索引及资源下载:/article/1443593.html

********************************************************************************************************************************
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: