This paper summarizes the commonly used brushes used to STL containers and some standard algorithms, including:
string、vector、map、pair、unordered_map、set、queue、priority_queue、stack,And the common operations of these containers, such as insertion, deletion, lookup, access (iterator or subscript, C++ 11 keyword auto understand? Sequential access to or random access), initialization, etc. Finally, we introduce several common functions of header files <, algorithm> and below.In particular, sort.
【string】C++String type
1.Insert operationstr.insert(pos,str);//Insert string STR at subscript POS
3.Intercept stringstring newstr = str.substr(pos,length)//Intercept the substring length length from the subscript pos.
4.Lookup operation1)str.find(str2)//If STR2 is a substring of str, return the location where STR2 first appears in str; otherwise, return string:: npos, which is – 1
5.String to digit functionstoi() , Such as string str=“123“,It can be int val=stoi (STR).
6.stringTypes support subscript access and iterator access, but typically use the subscript [] access, as in C. In addition, if you want to traverse a string completely after C++11, you can use the following method.
Simple example:
#include <cstdio> #include <iostream> #include <algorithm> #include <string> using namespace std; int main() { //stringCreation of objects string str1("aaa"); string str2="bbb"; char buf[10]="hello"; string str3(buf);//I didn't think it was possible to start the initialization method at first. cout<<str1<<' '<<str2<<' '<<str3<<endl<<endl; //insert string s="kill PAT"; cout<<"before insert: "<<s<<endl<<endl; s.insert(5,"fucking ");//Insertion at the original sequence s[5] cout<<"after insert: "<<s<<endl<<endl; //ergodic for(auto ch:s) cout<<ch; cout<<endl<<endl; //erase string s2="James go to Lakers Q"; cout<<s2<<endl; s2.erase(s2.end()-1);//Delete Q cout<<s2<<endl; s2.erase(s2.begin(),s2.begin()+6); cout<<s2<<endl; s2.erase(0,6); cout<<s2<<endl<<endl; //substr string s3="James go to Lakers Q"; string subStr=s3.substr(0,5)+" NB"; cout<<subStr<<endl<<endl; //find cout<<s3.find("s")<<endl;//4 cout<<s3.find("s",5)<<endl;//17 if(s3.find(".")==string::npos) cout<<"Not find\n";//Or write a number of s3.find (".") ==-1. else cout<<"Found\n"; return 0; }
In addition, non-string data can be converted to string data through sstream streams, which implements a function that splices various types of variables into strings (the same sprintf ()). Powerful, such as the following example, the int, space, sThe tring type and the char type are written into the ostringstream stream, and are finally spliced into string type outputs.
#include <iostream> #include <string> #include <sstream>//stringflow using namespace std; int main() { ostringstream oss; int a = 23; string str = "James"; char ch = 'X'; oss << a <<" "<< str << ch; string newStr = oss.str(); cout << newStr << '\n';//23 JamesX return 0; }
3.sprintfFormat of function:int sprintf( char *buffer, const char *format [, argument,…] );
#include <cstdio> int main() { char buf[100]; int a=422,b=100; double pi=3.1415926; int len=sprintf(buf,"%d %d %.2f",a,b,pi);//Splicing different values, the len returned is equivalent to strlen (buf). printf("len:%d, %s\n",len,buf); const char* str1="kill"; const char* str2="the fucking PAT"; sprintf(buf,"%s %s",str1,str2);//Two strings are stitching together. printf("%s\n",buf); char ch='A'; sprintf(buf,"I got %d in %s %c",b,str2,ch);//At the same time, different kinds of data are spliced together. printf("%s\n",buf); return 0; }
【vector】This is the most used, basically used as an array. But let’s talk a little bit about the early application space for two-dimensional arrays.
int main() { vector<vector<int>> matrix;//Suppose this is a matrix of 4*3. int row=4,col=3; matrix.resize(row); for(int i=0;i<matrix.size();i++) matrix[i].resize(col); //Next, you can access the subscript operation. matrix[1][2]=233; matrix[0][0]=422; for(int i=0;i<matrix.size();i++){ for(int j=0;j<matrix[i].size();j++){ printf("%d ",matrix[i][j]); } printf("\n"); } return 0; }
【map &&unordered_map】Don’t mix up in header files <, map>, and < unordered_map>, respectively.
#include <cstdio> #include <iostream> #include <map> #include <unordered_map> #include <string> using namespace std; int main() { //It can be used as a two-dimensional array int matrix[a][b] to represent a mapping relationship between a and B.//And the key value can be positive and negative, without constraints. unordered_map<int,unordered_map<int,bool>> mp; mp[11][-11]=true; mp[123][233]=true; printf("%d\n",mp[11][-11]);//1 printf("%d\n",mp[123][233]);//1 printf("%d\n",mp[8][9]);//The default value is 0. map<string,int> strToInt; //The three way to create map<...,..> object. strToInt.insert({"bbb",24}); strToInt.insert(make_pair("aaa",23)); strToInt.insert(pair<string,int>("ccc",3)); //Iterators traversed and found that the order of output has been sorted automatically based on key values, rather than in the order of insertion. for(map<string,int>::iterator it=strToInt.begin();it!=strToInt.end();it++) printf("%s %d\n",it->first.c_str(),it->second);//Notice that here is -> operator. printf("\n"); //delete strToInt.erase("aaa"); //C++11Of course, choose this kind of writing. for(auto it:strToInt) printf("%s %d\n",it.first.c_str(),it.second);//Here is the operator. return 0; }
【set】Commonly used in automatic sorting, to re emphasize. When elements stored in containers are structures, custom collation rules are required.
#include <iostream> #include <set> using namespace std; struct Node{ int id; int score; //Constructor Node(int id_,int score_):id(id_),score(score_){} //overload operators//According to grades, from high to low, if the grades are the same, then rank according to the number of students. bool operator <(const Node rhs) const {//These two const must be added. if(this->score != rhs.score) return this->score > rhs.score; else return this->id < rhs.id; } }; int main() { Node node1(1012,90); Node node2(1005,90); Node node3(1010,79); Node node4(1001,96); Node node5(1017,86); set<Node> mySet={node1,node2,node3,node4,node5}; //Iterator traversal for(set<Node>::iterator it=mySet.begin();it!=mySet.end();it++) cout<<it->id<<' '<<(*it).score<<'\n';//Iterator it is a pointer, so you can use -> or, first, you can use reference.//auto ergodic for(auto it:mySet) cout<<it.id<<' '<<it.score<<'\n'; return 0; }
【priority_queue】Priority queues are often used to find the maximum / minimum values of a sequence dynamically, such as greedy problems, or to optimize the Dijkstra algorithm. Using priority queues needs to know how the priority of elements in a queue is defined.
(1).Priority settings for basic data types
#include <iostream> #include <queue> #include <vector> #include <algorithm> using namespace std; int main() { //The default is arranged in descending order (large top stack), with a larger number of priorities.//The following two ways are equivalent.//priority_queue<int,vector<int>,less<int> > q1; priority_queue<int> q1; q1.push(3); q1.push(1); q1.push(3); q1.push(5); while(!q1.empty()){ cout<<q1.top()<<' ';//5 3 3 1 q1.pop(); } cout<<"\n"<<"\n"; //greater Let the smaller number of priorities be larger. priority_queue<int,vector<int>,greater<int> > q2; q2.push(3); q2.push(1); q2.push(3); q2.push(5); while(!q2.empty()){ cout<<q2.top()<<' ';// 1 3 3 5 q2.pop(); } return 0; }
(2).Priority settings for structure types
#include <cstdio> #include <queue> #include <vector> using namespace std; struct Node{ int id; int score; //Constructor Node(int id_,int score_):id(id_),score(score_){} //overload operators//According to grades, from high to low, if the grades are the same, then rank according to the number of students.//Note that the "<", ">" symbol here is the opposite of the custom sorting in front of set. bool operator <(const Node rhs) const { if(this->score != rhs.score) return this->score < rhs.score; else return this->id > rhs.id; } }; int main() { Node node1(1012,90); Node node2(1005,90); Node node3(1010,79); Node node4(1001,96); Node node5(1017,86); vector<Node> vec={node1,node2,node3,node4,node5}; priority_queue<Node> q; for(int i=0;i<vec.size();i++) q.push(vec[i]); while(!q.empty()){ Node node=q.top(); q.pop(); printf("%d %d\n",node.id,node.score); } return 0; }