1.unique();//這是一個去重函數,去掉相同的元素
sort(a,a+n,cmp);//必須先排序
n=unique(a,a+n)-a;//n爲數組a的個數
2.reverse();//前後翻轉。
reverse(a,a+n);//a爲數組(或字符),n爲長度
3.strcpy()與strncpy()的用法
博客鏈接:傳送門
#include<stdio.h>
#include<string.h>
int main()
{
char a[100]="hsdfkjfhs";
char b[100]="1232weioruiweruioo";
printf("%s\n",strncpy(a,b+2,sizeof(a)));//會把b中包括2號之後的賦給a,輸出32weioruiweruioo
return 0;
}
4.strstr(a,b);
它的作用找出b字符串在a字符串中第一次出現的位置(不包括b的串結束符)。返回該位置的指針,如找不到,返回空指針。
在做到這道題時用到了,題目鏈接:傳送門
strstr(a,b)
返回b在a中第一次出現的位置,返回指向這個位置的指針;
否則返回NULL(即假);
5.set之insert的用法。
insert可以把相同的統計爲一個,不會重複計數
#include<set>//3個頭文件
#include<iostream>
using namespace std;
set<string>ss;//定義set,你裏面可以是任何類型,int ,double
ss.insert(str);//將要統計的字符串放入ss中。
給個完整的代碼試試
#include<stdio.h>
#include<set>
#include<iostream>
using namespace std;
char str[1000];
int main()
{
int n;
while(~scanf("%d",&n))
{
set<string>ss;
for(int i=0; i<n; i++)
{
scanf("%s",str);
ss.insert(str);
}
printf("%d\n",ss.size());//輸出有多少種不同的字符串;
}
return 0;
}
6.lower_bound(),upper_bound(),的用法。
如果存在,下限找的是它本身的第一個,上限找的是它最後一個的下一個。
如果不存在,下限和上限一樣,找的是第一個大於這個數的數。
lower_bound()用法
例子:給你n個數,下標從0開始,輸入要找的數,輸出它的位置和該位置的那個數。
有各種情況,看下圖。
upper_bound()用法
例子:給你n個數,下標從0開始,輸入要找的數,輸出它的位置和該位置的那個數。
有各種情況,看下圖。
可以對比一下。
7.
stringstream ss;字符串流
清空的時候,兩個都寫,因爲有的時候,其中有時一個不管用(可能是我不會)。
ss.str("");
ss.clear();
ss.unget();將其中一個輸出的字符返回。
例題:D 前綴式計算
代碼:
#include<stdio.h>
#include<string>
#include<sstream>
#include<iostream>
#include<algorithm>
using namespace std;
stringstream ss;
double a;
char ch;
double solve()
{
ss>>ch;
switch(ch)
{
case '+':
return solve()+solve();
case '-':
return solve()-solve();
case '*':
return solve()*solve();
case '/':
return solve()/solve();
default:
ss.unget();
ss>>a;
return a;
}
}
int main()
{
string str;
while(getline(cin,str))
{
ss.clear();
ss<<str;
printf("%.2lf\n",solve());
}
return 0;
}
8.String:erase().
用於刪除String中的字母。
erase函數的原型如下:
(1)string& erase ( size_t pos = 0, size_t n = npos );
(2)iterator erase ( iterator position );
(3)iterator erase ( iterator first, iterator last );
也就是說有三種用法:
(1)erase(pos,n); 刪除從pos開始的n個字符,比如erase(0,1)就是刪除第一個字符
(2)erase(position);刪除position處的一個字符(position是個string類型的迭代器)
(3)erase(first,last);刪除從first到last之間的字符(first和last都是迭代器)
#include <string>
using namespace std;
int main ()
{
string str ("This is an example phrase.");
string::iterator it;
// 第(1)種用法
str.erase (10,8);
cout << str << endl; // "This is an phrase."
// 第(2)種用法
it=str.begin()+9;
str.erase (it);
cout << str << endl; // "This is a phrase."
// 第(3)種用法
str.erase (str.begin()+5, str.end()-7);
cout << str << endl; // "This phrase."
return 0;
}