CPP_mapの使い方 - アールメカブ

アールメカブ


CPP_mapの使い方

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;
 map<string, int>::iterator pa;
// 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++){
 if( (pa = m1.find(v[i])) != m1.end()){
 //すでにマップにあるのなら
      pa->second = pa->second + 1;
     //二つ目の数値を加算
   }
   else{// そうでないなら,データを挿入
     m1.insert(make_pair(v[i], 1) );
   }
 }
  // map の要素すべてにアクセスする
  cout << "map の内容の表示" << endl;
 pa = m1.begin();
 int n = (int)m1.size();
 
 for (int i = 0; i < n; i++) {
   cout << pa->first << " " << pa->second << endl;
   pa++;
 }
 
}
 
添付ファイル: filemap_test.cpp 599件 [詳細]
 
Link: Programming(4978d) Programming_C(5428d)
Last-modified: 2008-08-28 (木) 09:56:18 (5713d)