使用vector存放pair对象

阅读陈硕的《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是理所当然的。

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值