C++ for_each() 算法
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;
}