2011-10-21 3 views
0

私は約6種類のC++コンテナを使用しています。私は、コンテナの内容を出力するための印刷機能を書いていました。これは必要ですか?私はこれがC++ライブラリの一部だと思いますか?コンテナの印刷機能を書く必要性?

void print_list(const list<int>& list_int) 
    { 
    for (list<int>::const_iterator it = list_int.begin(); it != list_int.end(); it++) cout << *it << " "; 
    } 
    void print_um(const unordered_map<int, double>& map_int_d) 
    { 
    for(unordered_map<int, double>::const_iterator it = map_int_d.begin(); it != map_int_d.end(); ++it)cout << "[" << it->first << "," << it->second << "] "; 
    } 
+1

テンプレート付きのものを書く... –

+0

http://stackoverflow.com/q/4850473/485561をご覧ください。 – Mankarse

答えて

2

コードは、それが標準ライブラリの一部ではない理由についてのヒントを持って魅了される可能性があります。あなたのコードでは、大括弧とコンマを空白なしで使用してマップにペアを表示します。標準委員会の選択肢は次のようになっています。

  1. 多くの書式設定オプションを用意しています。
  2. フォーマットオプションがなく、フォーマットが気に入らない人は誰でも自分のロールを作ることができます。
  3. は何もしないし、誰もが彼らは図書館は、人々の特定のニーズを満たすように開発されるだろうことを知っオプション3と一緒に行った

自分自身をロールバックします。

+0

は私にとって意味があります –

4

それはライブラリの一部ではありませんが、提供されるツールで書くのはその簡単:要素pairである(のようなmapと私はunordered_mapを信じていると思います)コンテナの

C c; // Where C is a container type 
std::copy(
    c.begin(), c.end() 
    , std::ostream_iterator<C::value_type>(cout, " ") 
); 

あなたは」 dカスタム出力Iteratorを使用して、pairをカンマと括弧で印刷する必要があります。

+0

std :: copy()は何ですか? ? –

+0

@Chris Aaker:C++標準ライブラリの 'copy'アルゴリズム。 –

+0

OK ...ここにコピーされているもの...あなたの答えを詳しく調べることができます。それは非常に便利です。 –

1

何について:

#include <iostream> 
#include <map> 
#include <algorithm> 

template <typename K, typename V> 
    std::ostream& operator<<(std::ostream& os, const std::pair<K,V>& p) 
{ 
    return os << "[" << p.first << ", " << p.second << "]"; 
} 

template <typename Container> 
    std::ostream& operator<<(std::ostream& os, const Container& c) 
{ 
    std::copy(c.begin(), c.end(), 
     std::ostream_iterator<typename Container::value_type>(os, " ")); 
    return os; 
} 

また、あなたはあなたの質問に与える程度Boost Spirit Karma:

#include <boost/spirit/include/karma.hpp> 

using boost::spirit::karma::format; 
using boost::spirit::karma::auto_; 

int main() 
{ 
    std::vector<int> ints(1000); 
    std::map<std::string, int> pairs(); 

    // ... 

    std::cout << format(auto_ % " ", ints) << std::endl; 
    std::cout << format(('[' << auto_ << ',' << ']') % " ", pairs) << std::endl; 
} 
+2

最初の演算子は、 'std'名前空間にない(これはilegalなので)okであり、プログラムの残りの部分から幾分制約されています。 2番目のメソッドは、今や**すべての**がコンテナだけでなく 'operator << 'を持つという厄介な副作用を持っています。 –

+0

@ K-ballo:ええ、私は価値OPENAEが価値のある容器と会合容器のために表示されるようになるでしょう: – sehe

+0

これは私たちが概念を必要としている理由です... 'template ...' wouldトリックを完璧にやりなさい。 – HighCommander4

関連する問題