CPP_mapの使い方 のバックアップ(No.1) - アールメカブ

アールメカブ


CPP_mapの使い方 のバックアップ(No.1)


Programming

#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <ctime>
#include <functional>
#include <algorithm>
#include <boost/random.hpp>
// 「メルセンヌツイスター」( Seed=現在時刻 ) で
// 「小さな整数の一様乱数」( 1〜6 ) を生成

using namespace std;

// 柏原基礎知識実践編 p.74

class Random
{
public:
 // コンストラクタ
 Random(){ srand( (unsigned int)time(NULL) ); }
 
 unsigned int operator()(unsigned int max)
 {
   double tmp = static_cast<double>( rand() ) / 
          static_cast<double>( RAND_MAX );
   return static_cast<unsigned int>( tmp * max );
 }
 
};


int main(){
 string filename = "file.cpp.test";
 string str;
 vector<string> v;
 map<string, int> m1;
 pair<string, int> p;
 
 ifstream ifs(filename.c_str());// ファイルを開き
 if(!ifs){
   cout << "cant find file" << endl;
 }
 else{
   cout << "find file" << endl;
   while(!ifs.eof()){
     ifs >> str;
     v.push_back(str);//すべての行をベクトルに代入
     cout << str << endl;
   }
 }
 cout << "ランダム化の実行" << endl;
 Random r;
 random_shuffle(v.begin(), v.end(), r);
 cout << "ランダム後の表示" << endl;
 for(int i = 0; i < v.size(); i++){
   cout << v[i] << endl;
 }
 
 cout << "map への登録" << endl;
 for(int i = 0; i < v.size(); i++){
   //cout << v[i] << endl;
   if( (m1.find(v[i]))->second > 0){//すでにマップにあるのなら
     cout << "find" << endl;
     (m1.find(v[i]))->second = ( (m1.find(v[i]))->second) + 1;
     //二つ目の数値を加算
   }
   else{// そうでないなら,データを挿入
     p.first = v[i];
     p.second = 1;
     m1.insert(p);
     //	cout << "find " << endl;
   }
 }
  // map の要素すべてにアクセスする
  cout << "map の内容の表示" << endl;
 map<string, int>::iterator itr;
 itr = m1.begin();
 int n = (int)m1.size();
 
 for (int i = 0; i < n; i++) {
   cout << itr->first << " " << itr->second << endl;
   itr++;
 }
 
}