#include <iostream>
#include <map>
using namespace std;
typedef map<int, char, less<int> > result;
// map は int (学籍番号) の重複を許さないことに注意
// 重複を許すのは multimap
int main(){
result r;
r.insert(result::value_type(5,'B'));
r.insert(result::value_type(2,'A'));
r.insert(result::value_type(1,'D'));
r.insert(result::value_type(4,'F'));
r.insert(result::value_type(8,'A'));
r.insert(result::value_type(9,'C'));
// イテレータの利用
result::iterator pos;
for(pos = r.begin(); pos != r.end(); ++pos){
cout << pos->first << " " << pos->second << "\n";
// first が key で second が data
}
// 学籍番号 5 番の学生の成績は?
cout << "key=5, data=" << r[5] << "\n";
return(0);
}
|
#include <iostream>
#include <queue>
using namespace std;
class datapair{
int key;
char data;
public:
datapair(int k,char d):key(k), data(d){}
int getkey(){return key;}
char getdata(){return data;}
};
struct dataComparison{
bool operator () ( datapair * left, datapair * right){
return left->getkey() > right->getkey();
}
};
typedef priority_queue<datapair *,vector<datapair* >,dataComparison> result;
int main(){
result r;
r.push(new datapair(5,'B'));
r.push(new datapair(2,'A'));
r.push(new datapair(1,'D'));
r.push(new datapair(4,'F'));
r.push(new datapair(8,'A'));
r.push(new datapair(9,'C'));
while(!r.empty()){
cout << r.top()->getdata() << "\n";
// 最も学籍番号が小さいデータを表示
r.pop(); // 実際にはここで削除される。
}
return(0);
}
|