test.dat
1 2
1 3
1 5
3 5
2 4
#include<stdio.h> #include<iostream> #include<map> #include<string> #include<fstream> int main(){ using namespace std; FILE *fp; std::string index; std::string value; std::string str; char* str2; std::map<std::string,std::string> data; std::ifstream ifs("test.dat"); while(ifs && getline(ifs,str)){ str=strtok(const_cast<char*>(str.c_str())," "); str2=strtok(NULL," "); data[str]=str2; } map<string,string>::iterator it=data.begin(); while(it!=data.end()){ cout << (*it).first <<" "<< (*it).second << endl; ++it; } return 0; }
2列目の和を求める。
#include<stdio.h> #include<iostream> #include<map> #include<string> #include<fstream> int main(){ using namespace std; FILE *fp; std::string index; std::string value; std::string str; int str2; std::map<std::string,int> data; std::ifstream ifs("test.dat"); while(ifs && getline(ifs,str)){ str=strtok(const_cast<char*>(str.c_str())," "); str2=atoi(strtok(NULL," ")); data[str]=data[str]+str2; /* if(data.find(str)!=data.end()){ data[(str)]=str2+data[(str)]; }else{ data[(str)]=str2; } */ } map<string,int>::iterator it=data.begin(); while(it!=data.end()){ cout << (*it).first <<" "<< (*it).second << endl; ++it; } return 0; }