2015-10-30 19 views
0

我喜歡更多地瞭解模板。我試圖寫我自己的函數,它顯示每個容器元素。使用for_each函數顯示每個容器元素

void show_element(int i){ 
std::cout << i << endl; 
} 

int main(){ 

int dataarr[5]={1,4,66,88,9}; 
vector<int> data(&daten[0],&daten[0]+5); 

std::for_each(data.begin(),data.end(),show_element) 

... 

我的show_element函數還不是通用的。我如何編寫它,以便我可以將它用於不同的容器類型?

template <typename T> 
using type = typename T::value_type; 
void show_element(type i){ //type i must be sthg like *data.begin() 
std::cout << i << endl; 
} 

非常感謝

回答

2

更改爲:

template <typename T> 
void show_element(T const &i) { std::cout << i << std::endl; } 

for_each在區間[first提領每次迭代的結果應用給定的功能(例如,show_element),最後),爲了。所以你不需要使用容器的value_type。

在C++ 14

而且以上,你可以定義一個通用的λ:

auto show_element = [](auto const &i) { std::cout << i << std::endl; }; 

,並用它作爲:

int arr[] = {1, 4, 66, 88, 9}; 
std::vector<int> data(arr, arr + sizeof(arr)/sizeof(int)); 
std::for_each(arr, arr + sizeof(arr)/sizeof(int), show_element); 

LIVE DEMO

1

取而代之的是功能更的靈活使用課堂。在這種情況下,您可以將其他參數傳遞給功能對象。

例如,您可以指定要輸出元素的流或將會分離流中元素的分隔符。

類可以看起來如下方式

#include <iostream> 
#include <string> 
#include <vector> 
#include <algorithm> 

template <typename T> 
class show_elements 
{ 
public: 
    show_elements(const std::string &separator = " ", std::ostream &os = std::cout) 
     : separator(separator), os(os) {} 
    std::ostream & operator()(const T &value) const 
    { 
     return os << value << separator; 
    } 
protected: 
    std::string separator; 
    std::ostream &os; 
};  

int main() 
{ 
    int arr[] = { 1, 4, 66, 88, 9 };  
    std::vector<int> v(arr, arr + sizeof(arr)/sizeof(*arr)); 

    std::for_each(v.begin(), v.end(), show_elements<int>()); 
    std::cout << std::endl; 
} 

程序輸出是

1 4 66 88 9 
0

另一種簡單的方法是使用用於環路基於範圍的。

for(auto& element : container) { 
    cout<<element<<endl; 
} 
相關問題