Preface
Some time ago, some fans asked me, when I finished my freshman year, I didn't know how I am doing with c++? Have you got all the points you need to know? Are you getting started?
I have sorted out the C++ Basic and Core Advanced Knowledge Points in the last few days. If you haven't seen them, you can see them! Stay up late to burst the liver! C++ Basic Starter Collection
Stay up late to burst the liver! C++ Core Advanced Knowledge Points Compilation [10,000 words dry goods warning suggestions collection]
Continue to tidy up C++ Advanced STL Container string knowledge points today, let's take a look ~
The following contents are mainly summarized according to the online information. If there is any infringement, please trust me privately.
1 STL Initial Knowledge
1.1 The advent of STL
-
The software industry has always wanted to build something that can be reused
-
The object-oriented and generic programming ideas of C++ aim at improving the reusability
-
In most cases, data structures and algorithms fail to have a set of standards, forcing you to do a lot of duplicate work
-
STL emerged to establish standards for data structures and algorithms
1.2 Basic STL concepts
- STL: Standard Template Library
- STL is mainly divided into: container algorithm iterator
- Seamless connections between containers and algorithms are made through iterators.
1.3 Six components of STL
STL is generally divided into six components: container, algorithm, iterator, function-like, adapter (adapter), spatial Configurator
- Container: Various data structures, such as vector, list, deque, set, map, etc., are used to store data.
- Algorithms: Various commonly used algorithms, such as sort, find, copy, for_each et al
- Iterator: acts as a glue between the container and the algorithm.
- Similar function: behaves like a function and can be used as a strategy for an algorithm.
- Adapter: A device used to decorate containers or fake function or iterator interfaces.
- Space Configurator: Responsible for space configuration and management.
1.4 Containers, Algorithms, Iterators in STL
STL containers are designed to implement some of the most widely used data structures
Common data structures: arrays, chains, trees, stacks, queues, collections, mapping tables, etc.
These containers are divided into two types: sequential containers and associated containers:
Sequential container: Emphasizes the ordering of values. Each element in a sequential container has a fixed position.
Associated containers: Binary tree structure with no strict physical order between elements
Algorithms: Limited steps to solve logical or mathematical problems, a discipline we call Algorithms
The algorithms are divided into: deterioration algorithm and non-deterioration algorithm.
Qualitative algorithm: refers to the content of elements within an interval that will be changed during the operation. For example, copy, replace, delete, etc.
Non-metamorphic algorithm: refers to the operation process will not change the content of elements within the interval, such as find, count, traverse, search for extremes, and so on
Iterator: Provides a way to sequentially access the elements contained in a container without exposing its internal representation. Each container has its own iterator.
Iterator type:
type | function | Supports operations |
---|---|---|
Input Iterator | Read-only access to data | Read-only, support ++, ==,!= |
output iterators | Write-only access to data | Write-only, support++. |
forward iterators | Read and write and move iterators forward | Read and write, support ++, ==,!= |
Bidirectional Iterator | Read and write, and forward and backward | Read and write, support ++, -, |
random access iterators | Read-write operation, can access any data in a skip way, the most powerful iterator | Read and write, support ++, -, [n], -n, <, <=, >, >= |
The common types of iterators in containers are bidirectional iterators and random access iterators
Initial knowledge of 1.5 container algorithm iterator
The most common container in STL is Vector, which can be understood as an array. Let's see how to insert data into this container and traverse it
1.5. 1 vectors store built-in data types
Container: vector
Algorithms: for_each
Iterator: vector<int>::iterator
Case:
#include <vector> #include <algorithm> void MyPrint(int val) { cout << val << endl; } void test01() { //Create a vector container object and specify the type of data stored in the container through template parameters vector<int> v; //Place data in a container v.push_back(10); v.push_back(20); v.push_back(30); v.push_back(40); //Each container has its own iterator, which is used to traverse elements in the container //v.begin() returns an iterator that points to the first data in the container //v.end() returns an iterator that points to the next position of the last element of a container element //Vector<int>:: iterator gets the iterator type of vector<int>this container vector<int>::iterator pBegin = v.begin(); vector<int>::iterator pEnd = v.end(); //The first traversal method is: while (pBegin != pEnd) { cout << *pBegin << endl; pBegin++; } //The second traversal method is: for (vector<int>::iterator it = v.begin(); it != v.end(); it++) { cout << *it << endl; } cout << endl; //The third traversal method is: //Provide standard traversal algorithm header file algorithm using STL for_each(v.begin(), v.end(), MyPrint); } int main() { test01(); system("pause"); return 0; }
1.5.2 Vector holds custom data types
Case:
#include <vector> #include <string> //Custom Data Type class Person { public: Person(string name, int age) { mName = name; mAge = age; } public: string mName; int mAge; }; //Storage object void test01() { vector<Person> v; //Create data Person p1("aaa", 10); Person p2("bbb", 20); Person p3("ccc", 30); Person p4("ddd", 40); Person p5("eee", 50); v.push_back(p1); v.push_back(p2); v.push_back(p3); v.push_back(p4); v.push_back(p5); for (vector<Person>::iterator it = v.begin(); it != v.end(); it++) { cout << "Name:" << (*it).mName << " Age:" << (*it).mAge << endl; } } //Place Object Pointer void test02() { vector<Person*> v; //Create data Person p1("aaa", 10); Person p2("bbb", 20); Person p3("ccc", 30); Person p4("ddd", 40); Person p5("eee", 50); v.push_back(&p1); v.push_back(&p2); v.push_back(&p3); v.push_back(&p4); v.push_back(&p5); for (vector<Person*>::iterator it = v.begin(); it != v.end(); it++) { Person * p = (*it); cout << "Name:" << p->mName << " Age:" << (*it)->mAge << endl; } } int main() { test01(); test02(); system("pause"); return 0; }
1.5.3 Vector Container Nested Container
Case:
#include <vector> //Containers Nested Containers void test01() { vector< vector<int> > v; vector<int> v1; vector<int> v2; vector<int> v3; vector<int> v4; for (int i = 0; i < 4; i++) { v1.push_back(i + 1); v2.push_back(i + 2); v3.push_back(i + 3); v4.push_back(i + 4); } //Insert container elements into vector v v.push_back(v1); v.push_back(v2); v.push_back(v3); v.push_back(v4); for (vector<vector<int>>::iterator it = v.begin(); it != v.end(); it++) { for (vector<int>::iterator vit = (*it).begin(); vit != (*it).end(); vit++) { cout << *vit << " "; } cout << endl; } } int main() { test01(); system("pause"); return 0; }
2 STL - Common Containers
2.1 string container
2.1.1 string Basic Concepts
- String is a C++ style string, and string is essentially a class
string and char *Differences:
- char * is a pointer
- String is a class that encapsulates char*, manages this string, and is a container of char*.
Characteristic:
The string class encapsulates many member methods internally
For example, find, copy, delete, replace, insert
string manages the memory allocated by char* without worrying about copying and value crossings, etc. It is the responsibility of the class itself
2.1.2 string constructor
Constructor prototype:
- string(); // Create an empty string for example: string str;
string(const char* s); // Initialize with string s - String (const string & str); // Initialize another string object with one string object
- string(int n, char c); // Initialize with n characters C
Case:
#include <string> //string construction void test01() { string s1; //Create an empty string and call the parameterless constructor cout << "str1 = " << s1 << endl; const char* str = "hello world"; string s2(str); //Put c_string converted to string cout << "str2 = " << s2 << endl; string s3(s2); //Call copy constructor cout << "str3 = " << s3 << endl; string s4(10, 'a'); cout << "str3 = " << s3 << endl; } int main() { test01(); system("pause"); return 0; }
2.1.3 string assignment operation
Functional description:
- Assigning string s
Assignment function prototype:
- String & operator=(const char*s); // Char*type string assigns to the current string
- String & operator=(const string &s); // Assign string s to the current string
- String & operator=(char c); // Character assigns to the current string
- String & assign (const char *s); // Assign string s to the current string
- String & assign (const char *s, int n); // Assign the first n characters of string s to the current string
- String & assign (const string &s); // Assign string s to the current string
- String & assign (int n, char c); // Assign n characters C to the current string
Case:
//assignment void test01() { string str1; str1 = "hello world"; cout << "str1 = " << str1 << endl; string str2; str2 = str1; cout << "str2 = " << str2 << endl; string str3; str3 = 'a'; cout << "str3 = " << str3 << endl; string str4; str4.assign("hello c++"); cout << "str4 = " << str4 << endl; string str5; str5.assign("hello c++",5); cout << "str5 = " << str5 << endl; string str6; str6.assign(str5); cout << "str6 = " << str6 << endl; string str7; str7.assign(5, 'x'); cout << "str7 = " << str7 << endl; } int main() { test01(); system("pause"); return 0; }
2.1.4 string string stitching
Functional description:
- Implement splicing strings at the end of a string
Function prototype:
- String & operator+=(const char* str); // Overload+=Operator
- String & operator+=(const char c); // Overload+=Operator
- String & operator+=(const string & str); // Overload+=Operator
- String & append (const char *s); // Connect string s to the end of the current string
- String & append (const char *s, int n); // Connect the first n characters of string s to the end of the current string
- String & append (const string &s); // With operator+= (const string & str)
- String & append (const string &s, int pos, int n);// The n characters from POS in string s connect to the end of the string
Case:
//StringBuilder void test01() { string str1 = "I"; str1 += "Play games"; cout << "str1 = " << str1 << endl; str1 += ':'; cout << "str1 = " << str1 << endl; string str2 = "LOL DNF"; str1 += str2; cout << "str1 = " << str1 << endl; string str3 = "I"; str3.append(" love "); str3.append("game abcde", 4); //str3.append(str2); str3.append(str2, 4, 3); // Starting at subscript 4, truncate 3 characters and stitch them to the end of the string cout << "str3 = " << str3 << endl; } int main() { test01(); system("pause"); return 0; }
2.1.5 string Find and Replace
Functional description:
- Find: Find if the specified string exists
- Replace: Replace the string at the specified location
Function prototype:
- Int find (const string & str, int pos = 0) const; // Find where STR first appears, starting with pos
- int find(const char* s, int pos = 0) const; // Find where s first appears, starting with pos
- int find(const char* s, int pos, int n) const; // Find first position of the first n characters of s from POS position
- int find(const char c, int pos = 0) const; // Find the first occurrence of character c
- Int rfind (const string & str, int pos = npos) const; // Find the last str location, starting with pos
- int rfind(const char* s, int pos = npos) const; // Find the last occurrence of s, starting with pos
- int rfind(const char* s, int pos, int n) const; // Find the last position of the first n characters of s from POS
- int rfind(const char c, int pos = 0) const; // Find the last occurrence of character c
- String & replace (int pos, int n, const string & str); // Replace n characters from POS with string str
- String & replace (int pos, int n, const char* s); // Replace n characters from POS with string s
Case:
//Find and Replace void test01() { //lookup string str1 = "abcdefgde"; int pos = str1.find("de"); if (pos == -1) { cout << "not found" << endl; } else { cout << "pos = " << pos << endl; } pos = str1.rfind("de"); cout << "pos = " << pos << endl; } void test02() { //replace string str1 = "abcdefgde"; str1.replace(1, 3, "1111"); cout << "str1 = " << str1 << endl; } int main() { //test01(); //test02(); system("pause"); return 0; }
2.1.6 string string comparison
Functional description:
- Comparison between strings
Compare:
- String comparison is by character ASCII code
=returns 0
>Return 1
<Return-1
Function prototype:
- Int compare (const string &s) const; // Compare with string s
- int compare(const char *s) const; // Compare with string s
Case:
//string comparison void test01() { string s1 = "hello"; string s2 = "aello"; int ret = s1.compare(s2); if (ret == 0) { cout << "s1 Be equal to s2" << endl; } else if (ret > 0) { cout << "s1 greater than s2" << endl; } else { cout << "s1 less than s2" << endl; } } int main() { test01(); system("pause"); return 0; }
2.1.7 string character access
There are two ways to access a single character in a string
- Char & operator[] (int n); // Character retrieval by []
- Char&at(int n); // Getting characters through the at method
Example:
void test01() { string str = "hello world"; for (int i = 0; i < str.size(); i++) { cout << str[i] << " "; } cout << endl; for (int i = 0; i < str.size(); i++) { cout << str.at(i) << " "; } cout << endl; //Character Modification str[0] = 'x'; str.at(1) = 'x'; cout << str << endl; } int main() { test01(); system("pause"); return 0; }
2.1.8 string insert and delete
Functional description:
- Inserting and deleting string s
Function prototype:
- String & insert (int pos, const char* s); // Insert String
- String & insert (int pos, const string & str); // Insert String
- String & insert (int pos, int n, char c); // Insert n characters C at specified position
- String & erase (int pos, int n = n pos); // Delete n characters from Pos
Case:
//String Insertion and Deletion void test01() { string str = "hello"; str.insert(1, "111"); cout << str << endl; str.erase(1, 3); //3 characters from position 1 cout << str << endl; } int main() { test01(); system("pause"); return 0; }
2.1.9 string substring
Functional description:
- Get the desired substring from the string
Function prototype:
- String substr (int POS = 0, int n = n pos) const; // Returns a string of n characters starting with POS
Case:
//Substring void test01() { string str = "abcdefg"; string subStr = str.substr(1, 3); cout << "subStr = " << subStr << endl; string email = "hello@sina.com"; int pos = email.find("@"); string username = email.substr(0, pos); cout << "username: " << username << endl; } int main() { test01(); system("pause"); return 0; }
If this content is helpful to you, please comment on it three times, pay attention to it and support it with your collection.
Creation is not easy, lyrics are not good, your support and approval is the greatest power of my creation, we will see in the next article!
Dragon Junior
If there are any errors in this blog, please criticize and teach us. Thank you!