2017-03-21 14 views
0

それぞれの物の情報を表示することができます。C++ラムダ関数

void display(const Thing& c) 
{ 
    cout<<left<<setw(3)<<c.getKey()<<" "<<left<<setw(2)<<c.getLabel()<<endl; 
} 

template <typename E> 
void Graph<E>::bfsTraverse(FuncType func) 
{ 
    /* some code not necessary to describe */ 
} 

基本的に、ラムダ関数を使用してこれらを結びつける方法を理解する必要があります。

答えて

1

かなり簡単です。例えば、聞かせて、ラムダを使用して、ベクターのSプリント値:

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

int main (int argc, char* argv[]) { 
    std::vector <int> data{1,2,3,4}; 

    std::for_each (data.begin(), data.end(), [] (const int val) { std::cout << val << std::endl;}); 

    return 0; 
} 

最後の引数は、[](...)ラムダあります。あなたが次のことを行う必要があり、グラフの場合

template <typename E, typename FuncType> 
void Graph<E>::bfsTraverse (FuncType func) 
{ 
    /* some code not necessary to describe */ 
} 

UPDATE

: ラムダを受け入れる関数は、次のようになります。グラフの実装には、頂点にアクセスするためのメソッドが必要です: 'getRoot'、 'getSource'、 'getAllNodes'、それは実装定義です。私は 'getRoot'に固執します。各頂点/ノードには、 'getAdjacentVertices'、 'getChildren'などのメソッドが必要です。一緒に組み合わせる:

template <typename E, typename FuncType> 
void Graph<E>::bfsTraverse (FuncType func) 
{ 
    std::queue<Node> q; 

    auto&& root = getRoot(); 

    q.push (root); 

    while (not q.empty()) { 
     auto&& current = q.front(); 
     q.pop(); 

     func (current); 

     auto&& adjacent = current.getAdjacent(); 

     for (auto&& a: adjacent) { 
     q.push (a); 
     } 
} 

私は意図的に訪問先ノードなどのリストを保存しないように注意してください。しかしアイデア自体は変わりません。今度はこの関数を次のように呼び出すことができます:

Graph<E> g; 
g.bfsTraverse ([] (const Node& n) { 
        std::cout << n.to_str() << std::endl; 
       } 
);