C++ Standard Template Library (STL) - vector, set, string, map


One, vector

Vector is an "array whose length changes automatically as needed". In the algorithm, sometimes the use of ordinary arrays will exceed the memory. In this case, vector arrays can be used. In addition, the vector array can also be used to store graphs in the form of an adjacency list, which is very friendly to those who cannot use the adjacency matrix and are afraid of using pointers to implement the adjacency list.

To use vector, you need to add the header file #include<vector>. In addition, add the sentence "using namespace std".

1. The definition of vector:

vector<typename> name;

typename is the basic data type:

vector<int> name;
vector<double> name;
vector<char> name;
vector<node> name;//node是结构体类型

vector can also be an STL standard container, but in this case, a space should be added between >> when defining, because some compilers will consider it as a shift operation, resulting in a compilation error. as follows:

vector<vector<int> > name;

The above method can be associated with a two-dimensional array, and this two-dimensional vector array can be understood as a two-dimensional array whose two dimensions can have side lengths.

Define the vector array:

vector<typename> ArrayName[arraySize]; 

The above definition fixes the one-dimensional length to arraySize

2. Access to elements in the vector container:

Access by subscript: same as ordinary array, subscript from 0~vi.size()-1

Access through iterators: iterators can be understood as something similar to pointers

vector<typename>::iterator it;

In this way, the iterator it is obtained, and the elements inside can be accessed through *it

#include<stdio.h>
#include<vector>
using namespace std;

int main(){
    vector<int> vi;
    for(int i = 0 ; i < 5 ; i++)
        vi.push_back(i);//在vi末尾依次添加元素i
    vector<int>::iterator it = vi.begin();//it指向vi的首地址
    for(int i = 0 ; i < 5 ; i++)
        printf("%d ",*(it+i));
    return 0;
}

There is another way to access:

    //迭代器能够实现自增操作
    for(vector<int>::iterator it = vi.begin();it!=vi.end();it++)
        printf("%d ",*it);

3. push_back() function:
push_back(x) refers to adding an element x behind the vector, and the time complexity is O(1)

4. The pop_back() function
deletes the element at the end of the vector, and the time complexity is O(1)

#include<stdio.h>
#include<vector>
using namespace std;

int main(){
    vector<int> vi;
    for(int i = 0 ; i < 5 ; i++)
        vi.push_back(i);//在vi末尾依次添加元素i
    vi.pop_back();
    //迭代器能够实现自增操作
    for(vector<int>::iterator it = vi.begin();it!=vi.end();it++)
        printf("%d ",*it);
    return 0;
}

insert image description here

5. size()
gets the number of elements in the vector, and the time complexity is O(1)

6. clear()
is used to clear all elements in the vector

7. insert()
insert(it,x): used to insert an element x at any iterator it of the vector, and the time complexity is O(N)

#include<stdio.h>
#include<vector>
using namespace std;

int main(){
    vector<int> vi;
    for(int i = 1 ; i <= 5 ; i++)
        vi.push_back(i);//在vi末尾依次添加元素i
    vi.insert(vi.begin()+2,-1);//将-1插入到vi[2]的位置
    for(int i = 0 ; i < vi.size() ; i++)
        printf("%d ",vi[i]);
    return 0;
}

insert image description here

8. erase()
deletes a single element erase(it): deletes the element where the iterator is it

#include<stdio.h>
#include<vector>
using namespace std;

int main(){
    vector<int> vi;
    for(int i = 1 ; i <= 5 ; i++)
        vi.push_back(i);//在vi末尾依次添加元素i
    vi.erase(vi.begin()+2);//将-删除vi[2]
    for(int i = 0 ; i < vi.size() ; i++)
        printf("%d ",vi[i]);
    return 0;
}

insert image description here
erase(first,last): Delete elements in the [first,last) range

#include<stdio.h>
#include<vector>
using namespace std;

int main(){
    vector<int> vi;
    for(int i = 1 ; i <= 5 ; i++)
        vi.push_back(i);//在vi末尾依次添加元素i
    vi.erase(vi.begin()+2,vi.begin()+4);//将-删除vi[2]、vi[3]
    for(int i = 0 ; i < vi.size() ; i++)
        printf("%d ",vi[i]);
    return 0;
}

insert image description here
Common uses:

  • Can save space when the elements are uncertain
  • Since the number of output elements is uncertain in some occasions, in order to more conveniently process the last element that meets the conditions without outputting extra spaces, you can first use vector to record all the elements that need to be output and then output them all at once.
  • Storing graphs with adjacency lists

Two, set

set is a collection that is automatically ordered and cut without repeated elements. When using, you need to add #include< set > and using namespace std;

1. The definition of set:

set<typename> name;

The specific definition method is the same as vector

2. Access to elements in the set:
The set can only be accessed through iterators, and STL containers other than vector and String do not support the access method of *(it+i), so it can only be enumerated in the following way:

#include<stdio.h>
#include<set>
using namespace std;

int main(){
    set<int> st;
    st.insert(3);//将3插入st中
    st.insert(5);
    st.insert(2);
    st.insert(3);
    //注意:不支持it<st.end()写法
    for(set<int>::iterator it = st.begin();it!=st.end();it++)
        printf("%d ",*it);
    return 0;
}

insert image description here
It can be found that the elements in the set are automatically sorted incrementally and duplicate elements are removed

3. insert()
insert(x) can insert x into the Set container, and automatically increase the sorting and deduplication

4. find()
find(value) returns the iterator corresponding to value in the set

#include<stdio.h>
#include<set>
using namespace std;

int main(){
    set<int> st;
    for(int i = 1 ; i <=3 ; i++)
        st.insert(i);
    set<int>::iterator it = st.find(2);
    printf("%d",*it);
    return 0;
}

5、erase()

Delete a single element: st.erase(it), it is the iterator of the element to be deleted, which can be used in conjunction with the find() function; st.erase(value), value is the value of the element to be deleted

Delete elements in an interval: st.erase(first,last), delete elements in the interval [first,last)

#include<stdio.h>
#include<set>
using namespace std;

int main(){
    set<int> st;
    st.insert(20);
    st.insert(10);
    st.insert(40);
    st.insert(30);
    set<int>::iterator it = st.find(30);
    st.erase(it,st.end());//st.end()指向末尾元素的下一个位置,这里即删除30、40
    for(it = st.begin();it!=st.end();it++)
        printf("%d ",*it);
    return 0;
}

6. size()
is used to get the number of elements in the set

7. clear()
is used to clear all elements in the set

Three, string

In C language, the character array char str[] is generally used to store strings, and C++ introduces the string type, which encapsulates the common functions of strings. To use string, you need to add #include<string> and using namespace std; (string.h and string are different header files)

1. Definition of string:

string str;

string str1 = "abcd";

2. Access to content in string:
(1) Access by subscript:

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;

int main(){
    string str;
    cin>>str;
    for(int i = 0 ; i < str.length() ; i++)
        printf("%c",str[i]);
    return 0;
}

(2) Access through iterators:

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;

int main(){
    string str;
    cin>>str;
    for(string::iterator it = str.begin();it!=str.end();it++)
        printf("%c ",*it);
    return 0;
}

3. operator+=
can directly splice two strings together

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;

int main(){
    string str1,str2,str3;
    cin>>str1;
    cin>>str2;
    str3 = str1+str2;
    cout<<str3;
    return 0;
}

4. Compare operator
Two string types can use ==, !=, <, <=, >, >= to compare the size, and the comparison rule is dictionary order

5. length()/size()
length() returns the length of the string, that is, the number of characters stored

6. insert()
insert(pos, string), insert string at position pos

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;

int main(){
    string str1,str2;
    cin>>str1;
    cin>>str2;
    str1.insert(2,str2);
    cout<<str1;
    return 0;
}

insert image description here
insert(it, it2, it3): it is the position of the original string to be inserted, it2, it3 is the first iterator of the string to be inserted, indicating that the string [it2, it3) is inserted at the position of it

7. erase()
deletes a single element: str.erase(it) it is the iterator of the element to be deleted

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;

int main(){
    string str = "abcdefg";
    str.erase(str.begin()+4);
    cout<<str;
    return 0;
}

Delete elements in an interval: str.erase(first,last), delete elements in the interval [first,last)

Delete elements in a range: str.erase(pos,length), where pos is the starting position where elements need to be deleted, and length is the number of characters to be deleted

8. clear()
clears the data in string

9. substr()
substr(pos,len): starting from the pos bit, a string with a length of len

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;

int main(){
    string str = "Thank you for your smile.";
    cout<<str.substr(0,5)<<endl;//Thank
    cout<<str.substr(14,4)<<endl;//your
    cout<<str.substr(19,5)<<endl;//smile
    return 0;
}

10. string::npos
string::npos is a constant, its value itself is -1, but because it is an unsigned int type, it can also be considered as the maximum value of unsigned int. It is used as the return value of the find() function mismatch

11. find()
str.find(str2): When str2 is a string of str, return its first occurrence position in str, if str2 is not a string of str, return string::npos

str.find(str2, pos): start matching str2 from the pos position of str, the return value is the same as above

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;

int main(){
    string str = "Thank you for your smile.";
    string str2 = "you";
    if(str.find(str2)!=string::npos){
        cout<<str.find(str2)<<endl;
    }
    return 0;
}

12. replace()
str.replace(pos, len, str2): Replace str with a string starting from pos and having a length of len str2 str.replace(
it1, it2, str2): replace str's iterator [it1 , it2) string replacement bit str2 in the range

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;

int main(){
    string str = "Maybe you will turn around.";
    string str2 = "will not";
    string str3 = "surely";
    cout<<str.replace(10,4,str2)<<endl;
    cout<<str.replace(str.begin(),str.begin()+5,str3);
    return 0;
}

insert image description here

Four, map

map translates to mapping. map can map any primitive type (including STL containers) to any primitive type (including STL containers). To use map, you need to add #include< map > header file and using namespace std;

1. map definition

map<typename1,typename2> mp; //第一个是键的类型,第二个是值的类型,键是唯一的

If it is a mapping from string to integer, you must use string instead of char array

map<string,int> mp;

Access to elements in the map:
(1) Access by key (the key is unique):

#include<map>
#include<stdio.h>
using namespace std;

int main(){
    map<char,int> mp;
    mp['c'] = 20;
    mp['c'] = 30;
    printf("%d\n",mp['c']);//30
    return 0;
}

(2) Access through iterators

map<typename1,typename2>::iterator it;

Access keys via it->first, access values ​​via it->second

#include<map>
#include<stdio.h>
using namespace std;

int main(){
    map<char,int> mp;
    mp['m'] = 20;
    mp['r'] = 30;
    for(map<char,int>::iterator it = mp.begin();it!=mp.end();it++){
        printf("%c %d\n",it->first,it->second);
    }
    return 0;
}

The keys of the map will be automatically sorted from small to large

3. find():
find(key) returns the iterator of the map whose key is key

#include<map>
#include<stdio.h>
using namespace std;

int main(){
    map<char,int> mp;
    mp['m'] = 20;
    mp['r'] = 30;
    map<char,int>::iterator it = mp.find('m');
    printf("%c %d\n",it->first,it->second);//m 20
    return 0;
}

4. erase()
deletes a single element: mp.erase(it) it is the iterator of the de element to be deleted

Delete a single element: mp.erase(key): key is the key of the mapping to be deleted

Delete elements in a range: mp.erase(first, last), both first and last are iterators, and the range of deleted elements is [first, last)

5. size()
gets the logarithm mapped in the map

6. clear()
clears all elements in the map

Common uses:

  • Questions that need to establish a mapping between characters or strings and integers
  • For judging whether large integers or other types of data exist, map can be used as a bool array

Note: The keys and values ​​of the map are in one-to-one correspondence. If you want a key to correspond to multiple values, you need to use multimap

Guess you like

Origin blog.csdn.net/weixin_46025531/article/details/122797322