对与map的部分成员函数的测试
#include <iostream>
#include <map>
using namespace std;
void emplace_hintTest() // 往某个位置插入数据
{
map<char, int> mymap;
auto it = mymap.end();
it = mymap.emplace_hint(it, 'b', 10);
mymap.emplace_hint(it, 'a', 14);
mymap.emplace_hint(it, 'c', 14);
std::cout << "mymap contains:";
for (auto &x : mymap)
std::cout << " [" << x.first << ':' << x.second << ']';
std::cout << '\n';
}
void equal_rangeTest() // 找到与给予的 k 相同的 key 所含的 iterator ,左闭右开;
{
std::map<char, int> mymap;
mymap['a'] = 10;
mymap['b'] = 20;
mymap['c'] = 30;
std::pair<std::map<char, int>::iterator, std::map<char, int>::iterator> ret;
ret = mymap.equal_range('b');
std::cout << "lower bound points to: ";
std::cout << ret.first->first << " => " << ret.first->second << '\n';
std::cout << "upper bound points to: ";
std::cout << ret.second->first << " => " << ret.second->second << '\n';
}
void key_compTest() // 比较key的大小 默认 <
{
std::map<char, int> mymap;
std::map<char, int>::key_compare mycomp = mymap.key_comp();
mymap['a'] = 100;
mymap['b'] = 200;
mymap['c'] = 300;
std::cout << "mymap contains:\n";
char highest = mymap.rbegin()->first; // key value of last element
std::map<char, int>::iterator it = mymap.begin();
do
{
std::cout << it->first << " => " << it->second << '\n';
} while (mycomp((*it++).first, highest));
std::cout << '\n';
}
void lower_upper_boundTest() // lowwer >= upper > 未找到则返回 end()
{
std::map<char, int> mymap;
std::map<char, int>::iterator itlow, itup;
mymap['a'] = 20;
mymap['b'] = 40;
mymap['c'] = 60;
mymap['d'] = 80;
mymap['e'] = 100;
itlow = mymap.lower_bound('b'); // itlow points to b >=
itup = mymap.upper_bound('d'); // itup points to e (not d!) >
// mymap.erase(itlow, itup); // erases [itlow,itup)
// // print content:
// for (std::map<char, int>::iterator it = mymap.begin(); it != mymap.end(); ++it)
// std::cout << it->first << " => " << it->second << '\n';
cout << "*itlow = " << (*itlow).first << " *itup = " << (*itup).first;
}
void value_compTest() // 比较value放入的顺序 默认 < 即为先到
{
std::map<char, int> mymap;
mymap['x'] = 1001;
mymap['y'] = 2002;
mymap['z'] = 3003;
std::cout << "mymap contains:\n";
std::pair<char, int> highest = *mymap.rbegin(); // last element
std::map<char, int>::iterator it = mymap.begin();
do
{
std::cout << it->first << " => " << it->second << '\n';
} while (mymap.value_comp()(*it++, highest));
}
int main()
{
value_compTest();
return 0;
}
value_comp
注意这个函数不是比较value的大小
而是比较value放入的顺序 默认 < 即为先到