STL之拷贝和替换算法

来源:互联网 发布:php提示错误信息代码 编辑:程序博客网 时间:2024/06/07 01:21

STL之拷贝和替换算法

1.copy()

vector<int> vecIntA;vecIntA.push_back(1);vecIntA.push_back(3);vecIntA.push_back(5);vecIntA.push_back(7);vecIntA.push_back(9);vector<int> vecIntB;vecIntB.resize(5);          //扩大空间copy(vecIntA.begin(), vecIntA.end(), vecIntB.begin());  //vecIntB: {1,3,5,7,9}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

2.replace()

replace(beg,end,oldValue,newValue): 将指定范围内的所有等于oldValue的元素替换成newValue。

        vector<int> vecIntA;        vecIntA.push_back(1);        vecIntA.push_back(3);        vecIntA.push_back(5);        vecIntA.push_back(3);        vecIntA.push_back(9);        replace(vecIntA.begin(), vecIntA.end(), 3, 8);      //{1,8,5,8,9}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

3.replace_if()

replace_if : 将指定范围内所有操作结果为true的元素用新值替换。 
用法举例:

replace_if(vecIntA.begin(),vecIntA.end(),GreaterThree,newVal)

其中vecIntA是用vector声明的容器 
GreaterThree 函数的原型是 bool GreaterThree(int iNum)

//把大于等于3的元素替换成8vector<int> vecIntA;vecIntA.push_back(1);vecIntA.push_back(3);vecIntA.push_back(5);vecIntA.push_back(3);vecIntA.push_back(9);replace_if(vecIntA.begin(), vecIntA.end(), GreaterThree, 8);        // GreaterThree的定义在上面。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

4.swap()

swap: 交换两个容器的元素

vector<int> vecIntA;vecIntA.push_back(1);vecIntA.push_back(3);vecIntA.push_back(5);vector<int> vecIntB;vecIntB.push_back(2);vecIntB.push_back(4);swap(vecIntA, vecIntB);  //交换
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

5.综合代码

void main52_copy(){    vector<int> v1;    v1.push_back(1);    v1.push_back(3);    v1.push_back(5);    v1.push_back(7);    vector<int> v2;    v2.resize(v1.size() );    copy(v1.begin(), v1.end(), v2.begin());    printV(v2);}bool great_equal_5(int &n){    if (n>=5)    {        return true;    }    return false;}void main53_replace_replaceif(){    vector<int> v1;    v1.push_back(1);    v1.push_back(3);    v1.push_back(5);    v1.push_back(7);    v1.push_back(3);    replace(v1.begin(), v1.end(), 3, 8);    // >=5    replace_if(v1.begin(), v1.end(), great_equal_5, 1);    printV(v1);}void main54_swap(){    vector<int> v1;    v1.push_back(1);    v1.push_back(3);    v1.push_back(5);    vector<int> v2;    v2.push_back(2);    v2.push_back(4);    v2.push_back(6);    swap(v1, v2);    printV(v1);}
原创粉丝点击