改造後のプログラム:diction.txt(単語20159個)から引数で指定した単語とアルファベットの組み合わせが同じのグループを抜き出す。
疑問に思う点が主に2つ。
1.PS.hの比較関数はどうしてメンバ関数ではなく、関数オブジェクトなのですか?(これは元々で一切変更を加えてません)
2.メインプログラムの27行目がどうしてうまくグループを抜き出せるのですか?(これは自分が書きましたが、sortせずともうまくいったのは予想外です)
// PS.h ヘッダ
#ifndef _PAIR_IN_STRUCT
#define _PAIR_IN_STRUCT
#include<string>
#include<functional>
#include<algorithm>
using namespace std;
struct PS : pair<string,string>{
PS() : pair<string,string>(string(),string()){}
PS(const string &s) : pair<string,string>(s,s){ sort(first.begin(),first.end());}
operator string() const{return second;}
};
struct FirstLess : binary_function<PS,PS,bool>{
bool operator()(const PS &a,const PS &b){return a.first < b.first;}
}firstLess;
struct FirstEqual : binary_function<PS,PS,bool>{
bool operator()(const PS &a,const PS &b){return a.first == b.first;}
}firstEqual;
#endif
#include<iostream>
#include<iomanip>
#include<vector>
#include<iterator>
#include<fstream>
#include "PS.h";
#include <cassert>
using namespace std;
const int DICTION_SIZE = 20159;
ostream &error_message(ostream &stream){
stream << "Could not find the word";
return stream;
}
int main(int argc,char *argv[]){
char path[] = "C:\\Users\\Owner\\Desktop\\src\\diction.txt";
ifstream ifs(path);
assert(ifs!=NULL && argc>1);
vector<PS> dictionary;
dictionary.reserve(DICTION_SIZE);
copy(istream_iterator<string>(ifs),istream_iterator<string>(),back_inserter(dictionary));
sort(dictionary.begin(),dictionary.end(),firstLess);
while(--argc){
pair<vector<PS>::iterator,vector<PS>::iterator> pi = equal_range(dictionary.begin(),dictionary.end(),string(*++argv),firstLess);
if(pi.first==pi.second) cout << error_message;
copy(pi.first,pi.second,ostream_iterator<string>(cout,"\t"));
cout << endl;
}
return 0;
}