sort(按照自己的定义来排序)
sort函数用于C++中,对给定区间所有元素进行排序,默认为升序,也可进行降序排序。sort函数包含在头文件为#include的c++标准库中
vector<string>vec;
sort(vec.begin(), vec.end(), cmp); //修改排序方式
此外,可用内置函数直接修改升序降序
sort(vec.begin(), vec.end(),greater<int>()) //由大到小排序
sort(vec.begin(), vec.end(),less<int>()) //由小到大排序(sort本身就是默认由小到大)
sort(v.begin(), v.end(), cmp); //cmp函数可以自己定义
static bool cmp(string a, string b)
{ // 意为 按照连接起来更大的那个字符串来排序
return a+b > b+a;
}
例如:
“1” < "10".但“110”>"101" 因此排序顺位为“1” > "10"
注意:
- cmp函数必须用static修饰
- 返回值是bool类型的
sort如何返回索引值
vector<int>vec;
vector<int>::iterator it = find(vec.begin(),vec.end(),value);
if(it != vec.end()) //说明找到了
{
int ind = distance(vec.begin(),it);
}
if(it == vec.end()) //说明没找到
accumulate(vector求和)
可求vector所有元素进行求和操作,包含在头文件#include 的库函数中。
vector<string>vec;
int a = accumulate(vec.begin(), vec.end(), value);
//value 为累加初始值
lower_bound 、 upper_bound(返回vector的索引)
返回值为迭代器!!!
lower_bound:返回vector中第一个 小于等于 value的位置,即为插入的位置
upper_bound:返回vector中第一个 大于 value的位置
vector<int>vec;
int pos = lower_bound(vec.begin(),vec.end(),value) - vec.begin();
//由于lower_bound(vec.begin(),vec.end(),value)返回的是一个迭代器, 那么减去起始位置vec.begin(),就是value插入的位置