1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
#include <iostream>
#include <string>
#include <map>
using namespace std;
struct t_info{
int seats;
string id;
bool occupied;
};
int main(){
map<int, t_info> table;
// temp variable, setting members
cout << "add example 1 (key = 3)\n";
t_info info_3;
info_3.seats = 4;
info_3.id = "example 1";
info_3.occupied = false;
table[3] = info_3;
// temp variable, brace initialized
cout << "add example 2 (key = 8)\n";
t_info info_8 = {12, "example 2", true};
//t_info info_8{12, "example 2", true}; // alternative form for C++11
table[8] = info_8;
#if __cplusplus > 199711L
// brace initialize (C++11 and newer)
cout << "add example 3 (key = 14)\n";
table[14] = t_info({3, "example 3", true});
#else
cout << "skip example 3 as needs C++11\n";
#endif
// map::insert gives more control then []
//
// Note C++11 allows to use auto for insert's return type here, but spelling
// things out so can see what's up)
cout << "add example 4 (key = 3)\n";
// try to insert new, blank entry
pair<map<int, t_info>::iterator, bool> ret_3 = table.insert(make_pair(3, t_info()));
if(!ret_3.second) {
cout << "insert failed for 3 -- duplicate key!\n";
} else {
// would complete entry here if insert succeeded...
}
cout << "add example 4 (key = 29)\n";
// try to insert new, blank entry
pair<map<int, t_info>::iterator, bool> ret_29 = table.insert(make_pair(29, t_info()));
if(!ret_29.second) {
cout << "insert failed for 29 -- duplicate key!\n";
} else {
t_info& new_info = ret_29.first->second; // get reference to newly inserted entry
new_info.seats = 180;
new_info.id = "example 4";
new_info.occupied = false;
}
cout << "\n";
// list all entries
#if __cplusplus > 199711L
for(const auto pr : table) {
int key = pr.first;
const t_info& info = pr.second;
cout << "[" << key << "]\n"
<< "seats = " << info.seats << "\n"
<< "id = " << info.id << "\n"
<< "occupied = " << info.occupied << "\n"
<< "\n";
}
#else
map<int, t_info>::iterator i = table.begin();
while(i != table.end()) {
int key = (*i).first;
const t_info& info = (*i).second;
cout << "[" << key << "]\n"
<< "seats = " << info.seats << "\n"
<< "id = " << info.id << "\n"
<< "occupied = " << info.occupied << "\n"
<< "\n";
++i;
}
#endif
return 0;
}
|