1. 单个字符串排序 例:string a; 对a 进行排序:sort( a.begin(), a.end() ); 2. 字符串数组排序 例:string a[n]; 对a[n] 进行排序: sort(a, a+n) 。 可直接使用 sort,无需重写cmp方法,因为 string 类对 '>' ,'==', '<' 这些比较运算符进行了重载。 3. OJ 题练习 下面一道题验
sort(begin,end),表示一个范围,例如: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include "stdafx.h" #include <algorithm> #include "iostream" using namespace std; int main(int argc, char* argv[]) { int a[11]={2,4,5,6,1,2,334,67,8,9,0},i; for(i=0;i<...
class student{ public: student(const string &a, int b):name(a), score(b){} string name; int score; bool operator < (const student &m)const { return score< m.score; } }; int main() { vector< student> vect; student st1("Tom", 74); vect.push_back(st1); st1.name="Jimy"; ...
例:对数组 t 的第 0 到 len-1 的元素排序,就写 sort(t,t+len)。 对向量 v 排序也差不多, sort(v.begin(),v.end()); 排序的数据类型不局限于整数,只要是定义了小于运算的类型都可以,比如字符串类 string 。 如果是没有定义小于运算的数据类型,或者想改变排序的顺序,就要用到第三参数---比较函数。
begin(), v.end(), [](const string& s1, const string& s2) { return s1.size() < s2.size(); // 按长度升序 }); for (const auto& str : v) cout << str << " "; return 0; } 输出结果: a is this test hello world 1.6. 排序自定义类型 std::sort() 支持排序用户定义的类型...
它有三个参数sort(begin, end, cmp),其中begin为指向待sort()的数组的第一个元素的指针,end为指向待sort()的数组的最后一个元素的下一个位置的指针,cmp参数为排序准则,cmp参数可以不写,如果不写的话,默认从小到大进行排序。如果我们想从大到小排序可以将cmp参数写为greater<int>()就是对int数组进行排序,...
["peach"] = 5; msi["cherry"] = 10; vector<pair<string, int>> vpi(msi.begin(), msi.end()); sort(vpi.begin(), vpi.end(), cmp); for(auto item: vpi){ cout << item.first << " " << item.second << endl; } return 0; } // out /* watermelon 2 pear 3 apple 5 peach...
int main() { //初始化 vector<int>v = { 5,1,3,9,11 }; // [ ) //输出最大的元素,*表示解引用,即通过地址(迭代器)得到值 cout << *max_element(v.begin(), v.end()) << '\n'; } 497蓝桥题 —— 成绩分析 用户登录 #include <bits/stdc++.h> using namespace std; const int N...
接下来使用 sort(begin,end,compare(ASC)实现升序,sort(begin,end,compare(DESC)实现降序。 主函数为: 代码语言:javascript 代码运行次数:0 运行 AI代码解释 int main() { int a[20]={2,4,1,23,5,76,0,43,24,65},i; for(i=0;i<20;i++) cout<<a[i]<<endl; sort(a,a+20,compare(DESC))...
begin(), str.end()); #include <iostream> #include <algorithm> using namespace std; int main() { string str = "abcdefg"; //1 显示未翻转的字符串 cout << str << endl; //2 翻转数组,然后显示 reverse(str.begin(), str.end()); cout << str << endl; return 0; } // abcdefg ...