学习记录3.5

本文详细介绍了C++中的sort函数,包括基本用法、对字符串和整数数组的排序,以及在结构体数组上的应用。特别提到了STL容器vector、string和deque的sort使用限制。还讲解了pair和map的使用,以及红黑树在set和map中的作用。
摘要由CSDN通过智能技术生成

sort()函数

sort (start , end, 排序方法)   //默认从小到大

int a[100];  sort(a, a+100);//可对字符串排序 char a[100],sort(a, a+100, greater<char>());

sort(a, a+100, less<int>());  //降序

bool complare(int a, int b){  return a > b; }

sort(a, a+100, complare);

结构体数组的排序

struct student{
int x, y;   };

bool cmp(student a, student b)

{  return a.x > b.x;}//按x的降序

bool cmp(student a, student b)

{  if (a.x ==b.x)  return a.y < b.y;//x相同时y从小到大

  return a.x > b.x;//按x从大到小拍结构体

}

在STL标准容器中,只有vector、string、deque是可以使用sort的。
这是因为像set、map这种容器是用红黑树实现的(了解即可),元素本身有序,故不允许使用sort排序。

#include <cstdio>

#include <algorithm>

#include <string>

#include <iostream>

using namespace std;

int main ()

{ string a[3] = {"bbbb", "cc","aaa"};

sort(a, a+3);//按字典序升序

for (int i=0; i< 3; i++)  cout << a[i] << endl;

return 0;

}

pair的使用

map的使用

<map>//内部有序

map<映射前key, 映射后value> mp;

1.下标访问

map<char,int>mp;

mp['c']=20;

mp['c']=30;

printf("%d",m['c'])输出的是30;

2.迭代器访问

map<t1, t2>::iterator it;

find(key) //返回为key映射的迭代器

mp.erase(key) mp.erase(it);

mp.erase(first, last)//删除[first,last)

size();  clear(); // int l= mp.size();

查找:it = mp.find(1); //没找到返回的迭代器等于end()

mp.insert(pair<int, string>(1, "one"));

or mp[1]= "one";

for (it = mp.begin(); it != mp.end(); it ++) cout << it->first ;

typedef struct node {} NO;  申请变量时写NO n;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值