algorithm庫的常用函數
max(x,y) min(x,y) 參數可以是浮點數
abs(x) x必須是整數 如果x是浮點數則要用math頭文件下的fabs(x)
swap(x,y) 交換x和y
sort(首元素地址(必填),尾元素地址的下一個地址(必填),比較函數(非必填)) 例如sort(v.begin(),v.end())
比較函數:
bool cmp(node a,node b) // 結構體的比較函數
{
if(a.x!=b.x)
{
return a.x > b.x;
}
else
{
return a.y < b.y;
}
}
reverse(it,it2) it和it2可以是數組指針,也可以是容器的迭代器 注意的是翻轉範圍爲:[it,it2)。
lower_bound(first,last,value)、upper_bound(first,last,value),他們都要在一個有序數組或有序容器中使用,lower_bound在[first,last)中找第一個值大於等於value的元素的位置,upper_bound在[first,last)中找第一個值大於value的元素的位置,所以返回的是數組的指針或者是容器的迭代器,當然只要減去了首地址得到的也就是目標元素的下標了。
fill() 與memset不同,fill賦值可以是數組類型對應範圍中的任意值,因爲string.h頭文件中的memset中是按字節來賦值,因此往往只能賦值0或者-1而且速度比fill速度快。
float a[5] = {0.1,0.7,3.2,4.6,7.0};
for(int i=0;i<5;i++)
cout << a[i] << " ";
cout << endl;
cout << upper_bound(a,a+5,3) - a << endl;
reverse(a,a+5);
for(int i=0;i<5;i++)
cout << a[i] << " ";
cout << endl;
fill(a,a+5,3);
for(int i=0;i<5;i++)
cout << a[i] << " ";
return 0;
next_permutation() 給出一個序列在全排列中的下一個序列
int box[3]={1,2,3};
do{
for(int i=0;i<3;++i)
cout << box[i] << ' ';
cout << endl;
}while(next_permutation(box,box+3));
return 0;
string庫的常用函數
string的定義及初始化
string s1 = "hello"; //初始化字符串
string s2 ("world"); //另一種初始化
string s3; //初始化字符串,空字符串
string s4(5, 'a'); //s4由連續5個a組成,即s4="aaaaa";
string s5(s1,2,3); //從s1的2位置的字符開始,連續3個字符賦值給s5,即s5="llo";
string s6(s1, 1); //從s1的2位置的字符開始,將後續的所有字符賦值給s6,即s6="ello";
一整行讀入,可以使用getline():
string str;
getline(cin, str);
cout << str << endl;
重載的運算符
s1 = s2;
s1 += s2;
s1 = s2 + s3;
s1 == s2;
s1 = "s" + s2; //正確
s1 = "s" + "s"; //錯誤,加號兩邊至少要有一個string類型的對象
s1 = "s" + s2 + "s" + "s"; //正確
遍歷string
遍歷string中的元素時,我們可以使用類似C中的數組形式訪問,如s1[1],也可以使用STL特有的迭代器訪問:
string::iterator it;
for (it = s1.begin(); it != s1.end(); it++){
cout << *it << endl;
}
cout << *(s1.begin()); //正確,即訪問s1[0]
cout << *(s1.end()); //錯誤,s1.end()指向了空
插入insert()
string s1 = "hello";
s1.insert(1,"ins"); //從s1的1位置開始,插入"ins"字符串,即s1="hinsello";
s1.insert(1, "ins", 2);//從s1的1位置開始,插入"ins"字符串的前2個字符,即s1="hinello";
s1.insert(1, "ins", 1, 2);//從s1的1位置開始,插入"ins"字符串的從1位置開始的2個字符,即s1="hnsello";
刪除erase()
iterator erase(iterator first, iterator last);//刪除[first,last)之間的所有字符,返回刪除後迭代器的位置
iterator erase(iterator it);//刪除it指向的字符,返回刪除後迭代器的位置
string &erase(int pos = 0, int n = npos);//刪除pos開始的n個字符,返回修改後的字符串
查找find()
cout << s.find("aa", 0) << endl; //返回的是子串位置。第二個參數是查找的起始位置,如果找不到,就返回string::npos
if (s.find("aa1", 0) == string::npos)
{
cout << "找不到該子串!" << endl;
}