本周学习总结
万能头文件
#include<bits/stdc++.h>
using namespace std;
int main(){
std::ios::sync_with_stdio(false); //快速输入
…
}
sort函数
头文件#include<algorithm>
int num[4]={4,5,8,1};
sort(num,num+4) 默认从小到大排序
若想从大到小,,可在主函数前加一个bool函数
如:
bool cmp(int a,int b)
{ return a>b;
}
sort(num,num+4,cmp);
sort函数比一般的冒泡等排序法要快
且在结构体中也可应用
像例1中的加粗部位与例2中的加粗部位所展示的效果是一致的,但例2比例1的运行速率要快
例1:
#include<iostream>
using namespace std;
struct pp
{ int a;
int b;
};
int n,m;
int main()
{
while(cin>>n)
{ pp c[10000];
for(int q=0; q<n; q++)
{ cin>>c[q].a>>c[q].b;
}
** for(int q=0; q<n; q++)
{ for(int w=q+1; w<n; w++)
{ if(c[q].b>c[w].b)
{
swap(c[q],c[w]);
}
if(c[q].b==c[w].b)
{if(c[q].a<c[w].a)
{swap(c[q],c[w]);}
}
}}**
for(int q=0;q<n;q++)
{cout<<c[q].a<<" "<<c[q].b<<" ";}
cout<<endl;
m=c[0].a;
for(int q=1;q<n;q++)
{if(c[q].b!=c[q-1].b)
{m=m+c[q].a;}
}
cout<<m;
}
return 0;
}
例2:
#include<iostream>
#include<algorithm>
using namespace std;
struct pp{ int a;
int b;};
**bool cmp(pp a,pp b)
{if(a.b<b.b)
{return true;}
if(a.b>b.b)
{return false;}
else
{if(a.a>b.a)
{return true;}
else{return false;}}};**
int n;long long m;
int main()
{
while(cin>>n)
{ pp c[10000];
for(int q=0; q<n; q++)
{ cin>>c[q].a>>c[q].b; } **sort(c,c+n,cmp); **
m=c[0].a;
for(int q=1;q<n;q++)
{if(c[q].b!=c[q-1].b)
{m=m+c[q].a;}
}
cout<<m; }
return 0;}
去重函数unique
该函数的作用是去除容器或者数组中相邻元素的重复出现的元素 。
注意:
1.此去重并非真正意义上的去重,它没有将重复出现的元素删除,而是将它放到了数组或容器的末尾。
2.unique是针对相邻元素,所以使用前应该先排序,可使用sort函数。
(如例3中,定义数组a[]={5,3,6,4,3,6,4,1}输出的结果为6 5 4 3 1
如果将输出中的t改为n)
例3:
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{ return a>b;
}
int main()
{
int n,t;
cin>>n;
int a[100];
for(int q=0; q<n; q++)
{ cin>>a[q];
}
sort(a,a+n,cmp);
,(a,a+n)-a;
for(int q=0; q<t; q++)
{
cout<<a[q]<<" ";
}
return 0;
}
优先队列
头文件 #include<queue>
操作 :
q.push(elem)将元素elem置于优先队列
q.top()返回优先队列的下一个元素
q.pop()移出一个元素
q.size()返回队列中元素的个数
q.empty()返回优先队列是否为空
字符串string
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a;
while(cin>>a)
{ int x,y,z,g,f;
x=a.find("@");
f=a.find("@",x+1);
y=a.find(".");
z=a.find("@.");
g=a.find(".@");
if(x!=string::npos&&y!=string::npos&&z==string::npos&&g==string::npos&&f==string::npos)
{if(y>x&&x!=0&&y!=0&&x!=a.size()-1&&y!=a.size()-1)
{cout<<"YES";}
else
{cout<<"NO";}
}
else
{cout<<"NO";}}
return 0;
}
s.find(“a”)在字符串s中寻找字符a
s.find(“a”,x+1)在字符串s中从x+1位置开始寻找字符a
若该字符串中未找到字符a,则s.find(“a”)=string::npos
s.size()返回字符个数
s1+s2 将s2连接到s1之后
字符串中的字典序输出
两个字符串相等, 意味着这两个字符串长度相等 ,所包含的字符也完全相同 。
string a=“hello”
string b=“hello world”
string c=“Hello”
c>a b>a;