C++: コンテナ中の要素の出現頻度をカウントする
コード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | #include <iostream> #include <vector> #include <map> #include <algorithm> template < class InputIterator> std::vector<std::pair< typename InputIterator::value_type, int > > frequency(InputIterator first, InputIterator last) { typedef typename InputIterator::value_type ValType; typedef std::map<ValType, int > MapType; typedef std::vector<std::pair<ValType, int > > VecType; MapType m; for (InputIterator it = first; it != last; ++it) { if (m.find(*it) == m.end()) { m.insert( typename MapType::value_type(*it, 1)); } else { ++m[*it]; } } return VecType(m.begin(), m.end()); } // for utility template < typename T> std::ostream & operator<<(std::ostream & stream, std::vector<T> & v) { stream << "[" ; for (typeof(v.begin()) i = v.begin(); i != v.end(); ++i) { if (i != v.begin()) { stream << ", " ; } stream << *i; } stream << "]" ; return stream; } template < typename T, typename U> std::ostream & operator<<(std::ostream & stream, std::pair<T, U> & p) { stream << "(" << p.first << ", " << p.second << ")" ; return stream; } #define print(a) std::cout << a << std::endl #define all(a) (a).begin(),(a).end() // main using namespace std; int main( int argc, char **argv) { string apple = "apple" ; vector<pair< char , int > > a = frequency(all(apple)); print(apple << ": " << a); int xs[] = { 1, 3, 5, 4, 3, 2 }; vector< int > v(xs, xs + sizeof (xs) / sizeof (xs[0])); vector<pair< int , int > > b = frequency(all(v)); print(v << ": " << b); } |
出力例
1 2 | apple: [(a, 1), (e, 1), (l, 1), (p, 2)] [1, 3, 5, 4, 3, 2]: [(1, 1), (2, 1), (3, 2), (4, 1), (5, 1)] |
やはり、Scalaとかに比べるとストレスフルだなあ。
0 件のコメント:
コメントを投稿