先看字符串
getline:读取一行,可以读空格,存到字符数组里
gcount:当前读取的一行的字符数目
需要< cstring >
注意:数组下标从0开始。字符数目比输进来的多1(因为左闭右开)
char a[100];
cin.getline(a,100);
cout<<cin.gcount()<<endl;
string:string就是字符串,字符串操作。
string可以比较大小(字符串长度)。
string可以相加(直接接到后面)(不能减)
string substr可以读取字符区间(从0开始,但要到n)(左闭右开)
string empty可以判断字符串是否为空(返回bool)
string clear可以清空字符串
string find可以查找字符串位置(返回第一个字符的位置)
string find和substr组合起来可以直接找到这个位置的字符串
string a,b,c;
cin>>a>>b;
if(a < b) cout<<"a < b";
a += b;
cout<<a.substr(0,5)<<endl;
cout<<b.empty();
int pos = a.find("23");
string a1 = a.substr(pos);
注:这个pos是某种类型,返回的是一个区间的位置
char数组
char strr[100];
for(int i = 1;i <= 10;i ++)
cin>>strr[i];
gets(strr);
for(int i = 0;i <= strlen(strr);i ++)
cout << strr[i];
序列操作(排序,去重,翻转,排列)
sort
sort(a,a+10);//(左闭右开)
//sort可以根据你的规则来排序
bool cmp(int x,int y)
{
return x > y;
}
//___________________________________________________
/*
定义里一个bool型的函数返回值是bool型的在sort里面谁为true谁先。
这样就能降序了(原来是升序,<的话也是升序,>则是降序)
结构体数组按结构体元素排序:
*/
struct edge
{
int x;
int y;
int z;
}e[MAXN];
bool cmp(const edge &e1,const edge &e2)
{
return e1.x < e2.x;
}
//___________________________________________________
/*
或者多关键
先把关键1排完,关键1相同的排关键2。
*/
struct edge
{
int cost1;
int cost2;
}e[11];
bool cmp(edge x,edge y)
{
if(x.cost1 != y.cost1) return x.cost1<y.cost1;
else return x.cost2<y.cost2;
}
//___________________________________________________
//结果就是这样
in: out:
1 6 1 1
1 1 1 5
1 5 1 6
2 9 1 8
1 8 2 9
//———————————————————————————————————————————————————
//好吧,切正题,下面是神奇的翻转和去重
for(int i = 0;i < 10;i ++)
{
cin>>a[i];
}
sort(a,a + 10);
reverse(a, a + 10);//翻转就这么简单
int *b = unique(a,a + 10);
for(int i = 0;i < b - a;i ++) cout<<a[i]<<" ";
//注意:unique返回去重后序列的最后一项的下一项的指针 ,
//就是说返回现在不重的最后一个位置。所以for到b - a - 1。(左闭右开)
//___________________________________________________
//最后是排列
然后是最大最小值(不敢保证可以用)
但都是algorithm里的
这样就可以在区间找最大最小值了
cout<<*min_element(a,a+10)<<endl;
cout<<*max_element(a,a+10)<<endl;
未完待续