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

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

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

C++ series column:C++ dry goods store

Gitee: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 isan important part of the C++ standard library, not only a reusable A component library, and a software frameworkthat includes data structures and algorithms.


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 disclosed 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

Disadvantages 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 C++03 in the middle was basically 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. It is not in line with the ideas of OOP (Object-Oriented Programming and Process-Oriented), and the underlying space needs to be managed by the user. If you are not careful, you may access it out of bounds.

The string class in the standard library

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

Summarize

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_string<char,char_traits,allocator>string;

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;


Commonly used interface usage guide for 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 strings to construct string class objects
string(const string& s) copy constructor
void string_test1()
{
	//空类调用构造函数
	string s1;
	//调用构造函数
	string s2 ( "hello word");
	//调用拷贝构造函数
	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, call of const string class object
begin + end begin gets the iterator of the first character + end gets 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 method

//[]操作符重载遍历
	string s1("hello word");
	int i = 0;
	//遍历读
	for (int i = 0; i < s1.size(); i++)
	{
		cout << s1[i] << " "  ;
	}
	cout << endl;
	//遍历写
	for (int i = 0; i < s1.size(); i++)
	{
		s1[i]++;
		cout << s1[i] << " ";
	}
	cout << endl;
	//迭代器遍历
	string s2("hello word");
	//迭代器读
	string::iterator it = s2.begin();
	while (it != s2.end())
	{
		cout << *it<<" ";
		it++;
	}
	cout << endl;
	//迭代器写
	string::iterator it1 = s2.begin();
	//不可以写成while(it1<s2.end())
	//有可能不连续 
	while (it1 != s2.end())
	{
		*it1 = 'a';
		cout << *it1 << " ";
		it1++;
	}
	cout << endl;
	//范围for循环遍历
	//范围for循环读
	string s3("hello word");
	for (auto ch : s3)
	{
		cout << ch << " ";
	}
	cout << endl;
	//范围for循环写
	for (auto& ch : s3)
	{
		ch++;
		cout << ch << " ";
	}
	cout << endl;

 


Capacity operations on string class objects 

function name Function Description
size Returns the valid character length of the string
length Returns the effective length of the string
capacity Returns the total size of the space
clear Clear valid characters
reserve

Reserve space for string

resize Change the number of valid characters to n, and fill the extra space with the character c

 

	string s1("hello word");
	//这里size和length成员函数返回的都是字符串的长度
	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);
	//添加\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);
	//拿取前5个字符
	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;

 

 Opening rules for string class object space

	string s;
	s.reserve(100);
	int old = s.capacity();
	cout << "初始:" << old << endl;
	for (int i = 0; i < 100; i++)
	{
        //尾插
		s.push_back('x');
		if (s.capacity() != old)
		{
			cout << "容量:" << 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.

Notice:

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. Generally, size() is 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 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

function name Function Description
push_back Insert one character at the end
append Append a string
operator+= Append a string
assign n characters starting from pos position are overwritten to another string
insert Insert n characters at position pos
erase Delete the value after pos position
rfind Find the character c starting from the pos position of the string and return the position of the character in the string.
substr Search character c in str starting from pos position, intercept n characters, and then return them

End insert, append, += overload 

	string ss("world");
	string s;
	//尾插 一个字符
	s.push_back('#');
	cout << s << endl;
	//尾插一个字符串
	s.append("hello");
	cout << s << endl;
	//+=重载
	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);
	//覆盖
	cout << str << endl;
	//从第5个字符开始的10个字符覆盖过去
	str.assign(base, 5, 10);
	cout << str << endl;

insert、erase

	//在pos位置插入n个字符
	string str("hello world");
	str.insert(0,1, 'x');
	cout << str << endl;
	str.insert(str.begin(), 'x');
	cout << str << endl;
	//删除pos位置往后的值
	str.erase(5);
	cout << str << endl;

rfind、substr

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

 

Notice:

1. When appending characters to the end of string, the three implementation methods of s.push_back(c) / s.append(1, c) / s += 'c' are similar. In general, the string class + The = operation is commonly used, and the += operation can not only connect 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())
	{
		//读
		cout << *cit << " ";
		++cit;
		//不支持写
	}

 

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. Your support is my motivation to move forward!​ 

Preview of the next article - simulation implementation of string.

Guess you like

Origin blog.csdn.net/qq_55119554/article/details/134319122