C++ for_each() 算法


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;
}

 

1 2 3 4 5 6 7 8 9 10 11 12

請按任意鍵繼續. . .

 

代碼參考:C++標准庫(第2版)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM