阅读陈硕的《Linux多线程服务端编程》中以shared_ptr实现读写锁一节中,使用了map<string, vector<pair<string, int>>>。一般关联对象都会放在map或者hash_map中,这样做是为了查询速度快,SGISTL中map是红黑树结构,即每个节点要存放3个指针,分别是父节点,左子节点,右子节点,如果存入map的对象比较小且数量不多时,反而用有序vector会快一些。
当然vector本身没有sort(),需借助std::sort(),自己指定一个cmp算法来完成排序。
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
bool cmp(const pair<int, char>& a, const pair<int, char>& b)
{
return a.first < b.first;
}
int main()
{
vector<pair<int, char>> p;
p.push_back(make_pair(10, 'a'));
p.push_back(make_pair(9, 'c'));
p.push_back(make_pair(10, 't'));
p.push_back(make_pair(17, 'y'));
p.push_back(make_pair(10, 'b'));
sort(p.begin(), p.end(), cmp);
for (auto i = 0; i < p.size(); ++i)
cout << p[i].first << " " << p[i].second << endl;
cout << endl;
p.erase(p.begin());//erase delete element by iterator
for (auto i = 0; i < p.size(); ++i)
cout << p[i].first << " " << p[i].second << endl;
cout << endl;
cout << "end ele first: "<< p.end()->first << " second: " << p.end()->second << endl;
cout << "end ele first: "<< (end(p)-1)->first << " second: " << (end(p)-1)->second << endl;
p.erase(end(p)-1);
for (auto &i : p) //auto &i means can change
cout << i.first << " " << i.second << endl;
return 0;
}
不过我很纳闷为啥end()为啥能get到最后一个元素。也就是说end()和end()-1指向是一样的。当然照理end指向最后一个元素的下一个位置,使用end()-1是理所当然的。