C++結構いいかも

CでTRIEを実装してみようと思って、ハッシュが使えると便利なのにと思った。で、ふとC++を調べてみた。ハッシュもイテレータもあるし、stringとか実はCより扱いやすいし、結構便利だなと思った。さらに、boostを見たら、ものすごい勢いでいろいろ拡張されている。混沌としてるけど、いろんなパラダイムがあって、やっぱり使いたい部分を上手に使えるのだとしたら、C++って、結構いいのかもと思った。たぶん勘違いなんだろうけど。

#include <iostream>
#include <map>
#include <vector>
#include <iterator>
using namespace std;

static bool isOdd (const int &i) {
  return i % 2;
}

int main(void) {
  vector<int> v(10);
  generate(v.begin(), v.end(), rand);

  for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
    cout << *it << endl;
  }

  cout << endl;

  v.erase(remove_if(v.begin(), v.end(), isOdd), v.end());
  copy(v.begin(), --v.end(), ostream_iterator<int>(cout, "\n"));

  cout << endl;

  map<string,int> h;
  h["apple"] = 10;
  h["banana"] = 20;
  h["cinnamon"] = 30;

  map<string,int>::iterator it;

  for (it = h.begin(); it != h.end(); it++) {
    cout << (*it).first << ":" << (*it).second << endl;
  }

}

C++の何がいいってJavaと同じく速そうだし、コーディングコンテストに参加できそうで、それは楽しいかもと思ったりしている。早速、TopCoderの練習問題をサブミットしたら、ちゃんとテストにパスした。

#include <iostream>
using namespace std;

class CCipher {
public:
  string decode(string cipherText, int shift) {
    string buff;
    string::iterator it = cipherText.begin();
    while (it != cipherText.end()) {
      char c = *it++;
      c += shift;
      if (c > 'Z') c %= 'A';
      buff += c;
    }
    return buff;
  };
};

int main() {
  CCipher c;

  cout << c.decode("HAL", 1) << endl;
  return 0;
}