STL source code analysis: conceptual understanding of iterators, and code testing.

Purpose: To understand the source code of STL
The reason for iterators comes from a design pattern. It provides a method that allows users to access the data inside one by one, regardless of the structure of the data inside (tree, linear, array, graph, etc.). It is different from the access of the data structure, and it accesses the complete data uniformly one by one.
In STL, iterators can not only access the data inside one by one, but also serve as a glue to separate data structures and algorithms. The data structure and algorithm are separated, not only easy to read and write code, but also in line with the principle of opening and closing in development. If each data structure uses an algorithm, the algorithm can be developed elsewhere, and then iterators are used to glue the data structure and algorithm together. The specific test is as follows: There are three types of data structures: vector, list, and deque; one type of algorithm is find. The find algorithm is applied to these three data structures. The specific code is as follows:

#include<vector>
#include<list>
#include<deque>
#include<algorithm>
#include<iostream>

using namespace std;

int main()
{
    
    
	const int arraysize = 7;
	int ia[arraysize] = {
    
    0,1,2,3,4,5,6};
	vector<int> ivect(ia, ia+arraysize);
	list<int> ilist(ia, ia+arraysize);
	deque<int> ideque(ia, ia+arraysize);

	vector<int>::iterator it1 = find(ivect.begin(), ivect.end(), 4);
	if(it1 == ivect.end())
	{
    
    
		cout<<"4 not found in ivect.. "<<std::endl;
	}
	else
	{
    
    
		cout << "4 found in ivect..."<<std::endl;
	}

	list<int>::iterator it2 = find(ilist.begin(), ilist.end(), 5);
	if(it2 == ilist.end())
	{
    
    
		cout << "5 not found in ilist... " << endl;
	}
	else
	{
    
    
		cout << "5 found in ilist... " << endl;
	}

	deque<int>::iterator it3 = find(ideque.begin(), ideque.end(), 6);
	if(it3 == ideque.end())
	{
    
    
		cout << "6 not found in ideque... " << endl;
	}
	else
	{
    
    
		cout << "6 found in ideque... " << endl;
	}

	return 0;
}

In the code, the find function of the search function is applied to three data structures, and the test results are as follows:

insert image description hereIt can find 4,5,6. The search function is applied, which is also a very important role of the iterator.

Comprehension: The design of STL is very delicate, and the iterator is also a very important part, which provides a skill for future code design. In the future, try to separate the basic algorithm and data structure, and then use iterators to achieve the fusion of algorithm and data structure.

Guess you like

Origin blog.csdn.net/weixin_43851636/article/details/122258206