zoukankan      html  css  js  c++  java
  • 如何將container中的iterator,從一個值取代成另外一個值? (C/C++) (STL)

    Abstract
    若想將container中的iterator,從一個值取代成另外一個值,但container並沒有提供replace()這個member function,而是提供了replace()這個Generic Algorithm。

    Introduction
    以下範例我們將vector中,所有的1取代成4。

     1/* 
     2(C) OOMusou 2006 http://oomusou.cnblogs.com
     3
     4Filename    : GenericAlgo_replace.cpp
     5Compiler    : Visual C++ 8.0 / ISO C++
     6Description : Demo how to use replace() algorithm
     7Release     : 04/19/2006 1.0
     8*/

     9#include <iostream>
    10#include <vector>
    11#include <algorithm>
    12#include <sstream>
    13
    14using namespace std;
    15
    16int main() {
    17  int ia[] = {1,2,3};
    18  vector<int> ivec(ia, ia + sizeof(ia) / sizeof(int));
    19  replace(ivec.begin(), ivec.end(), 14);
    20  
    21  copy(ivec.begin(), ivec.end(), ostream_iterator<int>(cout, "\n"));
    22}


    執行結果

    4
    2
    3


    19行的

    replace(ivec.begin(), ivec.end(), 14);


    第一個參數傳入vector的起始位址,第二個參數傳入vector的結束位址,第三個參數是要被取代的值,第四個參數是要取代成的值。

    replace()完整的定義為

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


    其他相關的algorithm還有replace_if(),replace_copy(),replace_copy_if()。

    Conclusion
    初學者學習STL,對於STL的container僅提供有限的功能感到困擾,因為STL是基於泛型(GP : Generic Programming)下的產物,和物件導向的.NET Framework、Java SDK不同。在物件導向下,algorithm和container綁在一起,每個container都自給自足的提供自己的algorithm(member function),但這樣的缺點是,很多container都必須提供相同的基礎功能,這樣會造成class的肥大,且要重複寫相同的功能,如vector需提供replace(),那list、deque、stack怎麼辦?也要重新寫replace()嗎?泛型強調algorithm和container分離,而algorithm可以支援各種container,對於開發STL的人員來說,只要開發一次replace()即可,對於使用STL的人員來說,也只要學習一次replace()即可,而且將來若要從vector改成list,只需換掉container即可,其他程式都不須修改。

    所以使用STL時,若container沒有提供適當的功能,別忘了找找Generic Algorithm,也可順便欣賞這個由GP思維下library的beauty。

  • 相关阅读:
    面试题:使用存储过程造10w条测试数据,数据库插入10w条不同数据
    面试题:如何造10w条测试数据,在数据库插入10w条不同数据
    httprunner 2.x学习9-生成测试报告ExtentReport('dict object' has no attribute 'meta_data'问题已解决)
    httprunner 2.x学习8-参数化(引用 debugtalk 函数)
    httprunner 2.x学习7-参数化(引用外部csv数据)
    httprunner 2.x学习6-参数化与数据驱动
    httprunner 2.x学习5-测试用例集(testsuite)
    httprunner 2.x学习4-测试用例分层
    启动Hadoop HA Hbase zookeeper spark
    如何运行Spark程序
  • 原文地址:https://www.cnblogs.com/lzjsky/p/1861845.html
Copyright © 2011-2022 走看看