for_each() 算法非常灵活, 它允许你以不同的方式访问, 处理, 修改每一个元素, 自 C++11 起, for 循环提供了更方便更自然的行为, 因此, for_each() 恐将日渐丧失其重要性.
- algostuff.hpp
- #ifndef ALGOSTUFF_HPP
- #define ALGOSTUFF_HPP
- #include <array>
- #include <vector>
- #include <deque>
- #include <list>
- #include <forward_list>
- #include <set>
- #include <map>
- #include <unordered_set>
- #include <unordered_map>
- #include <algorithm>
- #include <iterator>
- #include <functional>
- #include <numeric>
- #include <iostream>
- #include <string>
- // 集合中添加元素
- template <typename T>
- inline void INSERT_ELEMENTS(T& coll, int first, int last)
- {
- for (int i=first;i<=last;++i)
- {
- coll.insert(coll.end(),i);
- }
- }
- // 输出集合中的元素
- template <typename T>
- inline void PRINT_ELEMENTS(const T& coll,const std::string & optcstr="")
- {
- std::cout <<optcstr;
- for (auto elem:coll)
- {
- std::cout << elem << ' ';
- }
- std::cout << std::endl;
- }
- // 输出 Map 中的元素
- template<typename T>
- inline void PRINT_MAPPED_ELEMENTS(const T& coll, const std::string& optcstr = "")
- {
- std::cout <<optcstr;
- for (auto elem:coll)
- {
- std::cout << "[" << elem.first << "," << elem.second << "]";
- }
- std::cout << std::endl;
- }
- #endif // !ALGOSTUFF_HPP
- main.cpp
- #include "algostuff.hpp"
- using namespace std;
- int main()
- {
- vector<int> vec1;
- INSERT_ELEMENTS(vec1,1,12);
- for_each(vec1.cbegin(), vec1.cend(),
- [](int elem)
- {
- cout << elem << " ";
- });
- system("pause");
- return 0;
- }
- 1 2 3 4 5 6 7 8 9 10 11 12
请按任意键继续. . .
代码参考: C++ 标准库 (第 2 版)
来源: http://www.bubuko.com/infodetail-3360867.html