[C++ dry goods store] Brief introduction to STL | Guide to using string class

================================================ ==========================

Click to go directly to the personal homepage: Xiaobai is not a program Yuan

C++ Series Column: C++ Dry Goods Shop

Code repository: Gitee

================================================ ==========================

Table of Contents

What is STL

STL version

The six major components of STL

Disadvantages of STL

string class

String in C language

The string class in the standard library

Commonly used interface usage guide for string class

Common constructs in the string class

Access and traversal operations of string class objects

Capacity operations on string class objects

Opening rules for string class object space

Modification operation of string class object

End insert, append, + = overload

assign

insert, erase

rfind, substr

Three interesting iterators

Inverse iterator

static iterator

static inverted iterator


What is STL

STL (standard template libaray-standard template library): It is an important part of the C++ standard library. It is not only a reusable component library, but also a includes data structures and algorithms. software frameworks.

STL version

  • Original copy

The original version completed by Alexander Stepanov and Meng Lee at HP Labs, in the spirit of open source, states that anyone is allowed to use, copy, modify, disseminate, and commercially use these codes without paying. The only condition is that it needs to be used as open source like the original version. HP version – the ancestor of all STL implementation versions.

  • P.J. version

Developed by P. J. Plauger, it is inherited from the HP version and adopted by Windows Visual C++. It cannot be made public or modified. Defects: low readability and weird symbol naming.

  • RW version

Developed by Rouge Wage Company, it is inherited from the HP version and adopted by C++Builder. It cannot be made public or modified, and its readability is average.

  • SGI version

Developed by Silicon Graphics Computer Systems, Inc., it is inherited from the HP version. Adopted by GCC (Linux), it has good portability and can be disclosed, modified and even sold. From the naming style and programming style, it is very readable. The technical content of STL we will share later requires reading part of the source code, and the main reference is this version.

The six major components of STL

  • 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, etc.
  • Iterator: acts as the glue between container and algorithm
  • Functor: behaves like a function and can be used as a strategy for an algorithm
  • Adapter: something used to decorate a container or functor or iterator interface
  • Space adapter: responsible for space configuration and management

Defects of STL

1. The update of the STL library is too slow. This is a serious complaint. The last version was C++98, and the middle one, C++03, has basically been revised. It has been 13 years since C++11 came out, and STL has been further updated.
2. STL currently does not support thread safety. In a concurrent environment, we need to lock ourselves. And the lock granularity is relatively large.
3. STL’s extreme pursuit of efficiency leads to internal complexity. Such as type extraction, iterator extraction.
4. The use of STL will cause code expansion problems. For example, using vector/vector/vector will generate multiple copies of code. Of course, this is caused by the template syntax itself.

string class

Why do we need to study and analyze the string class in depth?

String in C language

In C language, a string is a collection of characters ending with ‘\0’. For convenience of operation, the C standard library provides some str series library functions, but these library functions are separated from strings and are not very specific. It conforms to the ideas of OOP (Object-Oriented Programming and Process-Oriented), and the underlying space needs to be managed by the user himself, and he may even access it out of bounds if he is not careful.

string class in the standard library

1. String is a class that represents a sequence of characters
2. The standard string class provides support for such objects. Its interface is similar to that of the standard character container, but adds design features specifically for operating single-byte character strings.
3. The string class uses char (that is, as its character type, using its default char_traits and allocator type (see basic_string for more information on templates).
4. The string class is an instance of the basic_string template class. It uses char to instantiate the basic_string template class, char_traits
and allocator as the default parameters of basic_string (please refer to basic_string for more template information).
5. Note that this class handles bytes independently of the encoding used: if a column is used to handle multibyte or variable-length characters (such as UTF-8), all members of this class (such as length or size) and its The iterator will still operate in terms of bytes (rather than actual encoded characters).

Summary

1. string is a string class that represents a string

2. The interface of this class is basically the same as that of a regular container, and some regular operations specially used to operate strings are added.

3. The underlying string is actually:

Alias of basic_string template class, typedefbasic_stringstring;

4. Multi-byte or variable-length character sequences cannot be operated.

When using the string class, you must include the #include header file and using namespace std;

Guidelines for the use of commonly used interfaces of the string class

Common constructs in the string class

Function name Function Description
string() Construct an empty string class object, that is, an empty string
string(const char* s) Use constant string to construct string class object
string(const string & amp; s) Copy constructor
void string_test1()
{
//Empty class calls constructor
string s1;
//Call constructor
string s2 ("hello word");
//Call copy constructor
string s3(s2);
cin >> s1;
cout << "s1:" << s1 << endl;
cout << "s2:"<<s2 << endl;
cout << "s3:"<<s3 << endl;
}

Access and traversal operations of string class objects

Function name Function description
operator[ ] Returns the character at pos position, Calling const string class objects
begin + end begin gets the first Iterator of characters + end to get the iterator of the next position
rbegin + rend

rbegin gets the reverse iterator of the last character + rend gets the iterator of the first character

Range for loop

C++11 concise range for loop new traversal way

//[] Operator overload traversal
string s1("hello word");
int i = 0;
//Traverse and read
for (int i = 0; i < s1.size(); i + + )
{
cout << s1[i] << " " ;
}
cout << endl;
//Traverse and write
for (int i = 0; i < s1.size(); i + + )
{
s1[i] + + ;
cout << s1[i] << " ";
}
cout << endl;
//Iterator traverse
string s2("hello word");
//Iterator read
string::iterator it = s2.begin();
while (it != s2.end())
{
cout << *it<<" ";
it++;
}
cout << endl;
//iterator write
string::iterator it1 = s2.begin();
//Cannot be written as while(it1<s2.end())
//may be discontinuous
while (it1 != s2.end())
{
*it1 = 'a';
cout << *it1 << " ";
it1++;
}
cout << endl;
//Range for loop traversal
//Range for loop reading
string s3("hello word");
for (auto ch : s3)
{
cout << ch << " ";
}
cout << endl;
//Write in range for loop
for (auto & ch : s3)
{
ch + + ;
cout << ch << " ";
}
cout << endl;

Capacity operation of string class object

Function name Function description
size Return the effective character length of the string
length Return Effective length of string
capacity Return total space size
clear Clear valid characters
reserve

Reserve space for string

resize Change the number of valid characters to n, the extra space is filled with the character c
 string s1("hello word");
//The size and length member functions here return the length of the string.
cout << s1.size() << endl;
cout << s1.length() << endl;
cout << s1.capacity() << endl;
s1.clear();
cout << s1.capacity() << endl;

 string s1("hello word");
cout << s1 << endl;
cout << s1.size() << endl;
cout << s1.capacity() << endl;
s1.resize(13);
//Add\0
cout << s1 << endl;
cout << s1.size() << endl;
cout << s1.capacity() << endl;
s1.resize(20, 'x');
cout << s1 << endl;
cout << s1.size() << endl;
cout << s1.capacity() << endl;
s1.resize(5);
//Get the first 5 characters
cout << s1 << endl;
cout << s1.size() << endl;
cout << s1.capacity() << endl;
string s2;
s2.resize(10, '#');
cout << s2 << endl;
cout << s2.size() << endl;
cout << s2.capacity() << endl;
s2[0] + + ;
cout << s2 << endl;
s2.at(0) + + ;
cout << s2 << endl;

Development rules for string class object space

 string s;
s.reserve(100);
int old = s.capacity();
cout << "Initial:" << old << endl;
for (int i = 0; i < 100; i + + )
{
        //Tail insert
s.push_back('x');
if (s.capacity() != old)
{
cout << "Capacity:" << s.capacity() << endl;
old = s.capacity();
}
}
s.reserve(10);
cout << s.capacity() << endl;

First of all, in the vs integrated development environment, more space will be opened up at our request.

In the vs integrated development environment, the space will be opened at 1 times at first, and finally it will be opened at 1.5 times.

Note:

1. The underlying implementation principles of the size() and length() methods are exactly the same. The reason for introducing size() is to be consistent with the interfaces of other containers. Under normal circumstances, size() is basically used.

2. clear() only clears the valid characters in the string and does not change the underlying space size.

3. resize(size_t n) and resize(size_t n, char c) both change the number of valid characters in the string to n. The difference is that when the number of characters increases: resize(n) uses 0 to fill in more characters. Out of the element space, resize(size_t n, char c) uses character c to fill the extra element space. Note: When resize changes the number of elements, if the number of elements is increased, the size of the underlying capacity may be changed. If the number of elements is reduced, the total size of the underlying space remains unchanged.

4. reserve(size_t res_arg=0): Reserve space for string without changing the number of valid elements. When the parameter of reserve is less than the total size of the underlying space of string, reserve will not change the capacity.

Modification operation of string class object

td>

Function name Function description
push_back Insert a character at the end
append Append a string
operator + = Append a string
assign from pos The n characters starting at the position are overwritten into another string
insert Insert n characters at the pos position
erase Delete the value after pos position
rfind Start from the string pos position and move forward Find the character c and return the position of the character in the string
substr Look for the character c starting from the pos position in str and intercept n characters, then it will be returned

Tail plug, append, + = overload

 string ss("world");
string s;
//Insert one character at the end
s.push_back('#');
cout << s << endl;
//Insert a string at the end
s.append("hello");
cout << s << endl;
// + = overload
s + = '#';
s + = "hello";
cout << s << endl;
s.append(ss);
cout << endl;

assign

 string str("xxxxxxx");
string base = "The quick brown fox jumps over a lazy dog.";
str.assign(base);
//overwrite
cout << str << endl;
//Overwrite the 10 characters starting from the 5th character
str.assign(base, 5, 10);
cout << str << endl;

insert、erase

 //Insert n characters at position pos
string str("hello world");
str.insert(0,1, 'x');
cout << str << endl;
str.insert(str.begin(), 'x');
cout << str << endl;
//Delete the value after pos position
str.erase(5);
cout << str << endl;

rfind, substr

 string s1("test.cpp");
int i = s1.rfind('.');
cout << s1.substr(i) << endl;

Note:

1. When appending characters to the end of a string, the three implementation methods of s.push_back(c) / s.append(1, c) / s + = ‘c’ are similar. Generally, the + = operation of the string class uses comparison. Many, the + = operation can not only concatenate single characters, but also strings.

2. When operating on strings, if you can roughly estimate how many characters will be placed, you can first reserve the space through reserve.

Three interesting iterators

Inverse iterator

In the study of C language, we will encounter the problem of inversion, but the string class in C++ contains this member function

 string s4("hello word");
//string::reverse_iterator itr = s4.rbegin();
auto itr = s4.rbegin();
while (itr != s4.rend())
{
cout << *itr << " ";
itr + + ;
}

Here you can see the role of the auto keyword.

Static iterator

 const string s1("hello word");
string::const_iterator cit = s1.cbegin();
while (cit != s1.cend())
{
\t\t//read
cout << *cit << " ";
+ +cit;
//Does not support writing
}

static inverted iterator

 const string s1("hello word");
string::const_reverse_iterator crt = s1.crbegin();
auto crt = s1.crbegin();
while (crt != s1.crend())
{
cout << *crt << " ";
crt + + ;
}

Today’s sharing ends here! If you think the article is good, you can support it three times in a row. Your support is the driving force for me to move forward!

Preview of the next article – simulation implementation of string.