C++: コンテナ中の要素の出現頻度をカウントする
コード
#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); }
出力例
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 件のコメント:
コメントを投稿