加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c++STL之常用遍历算法

发布时间:2020-12-16 09:06:57 所属栏目:百科 来源:网络整理
导读:需要引入头文件#includealgorithm 1.for_each #includeiostream using namespace std;#include vector #include algorithm class MyPrint { public : void operator ()( int val) const { cout val " " ; } }; void printVector( int val) { cout val ;} voi

需要引入头文件#include<algorithm>

1.for_each

#include<iostream>
using namespace std;
#include <vector>
#include <algorithm>

class MyPrint {
public:
    void operator()(int val) const{
        cout << val << " ";
    }    
};

void printVector(int val) {
    cout << val << ;
}

void test() {
    vector<int> v1;
    for (int i = 0; i < 10; i++)
    {
        v1.push_back(i);
    }
    //利用普通函数
    for_each(v1.begin(),v1.end(),printVector);
    cout << endl;
    利用仿函数
 endl;
}


 main() {
    test();
    system("pause);
    return 0;
}

2.transform:将容器搬运到另一个容器中

#include<iostream>
 Transform {
int {
        这里可以对val进行一些判断
        return val;
    }    
};
 {
        cout << val << ;
    }
};

)
    {
        v1.push_back(i);
    }
    vector< v2;
    目标容器需要先开辟空间
    v2.resize(v1.size());
    transform(v1.begin(),v2.begin(),Transform());
    for_each(v2.begin(),v2.end(),1)">;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读