The interface between vector and list introduces how to use and distinguish, with code attached.

Posted by knight on Tue, 04 Jan 2022 00:59:47 +0100

1, vector

Vector is a sequential container that encapsulates dynamic size arrays. It can store various types of objects. It can be considered that a vector is a dynamic array that can store any type.

Function implementation:

1. Constructor:

vector() parameterless construction
vector (size_type n, const value_type & val = value_type()) constructs and initializes n Vals
vector (const vector& x); Copy constructs (only vectors of the same type can be copied)
vector (InputIterator first, InputIterator last); Initializing constructs using iterators

std::vector<int> first;                //Parameterless construction, create an empty vector
std::vector<int>second(4,100);         //Initialize the construction vector to four 100
std::vector<int>third(second.begin(),second.end());     //Initializing constructs using iterators
std::vector<int>fourth(third);         //copy construction         

2. Use of vector iterator (just like a pointer)

begin() gets the iterator of the first data location
end() gets the iterator of the next location of the last data
rbegin() gets the reverse of the last data location_ iterator
rend() gets the reverse of the previous position of the first data_ iterator
cbegin() gets const of the first data location_ iterator
cend() gets const of the next location of the last data_ iterator

 3.vector space growth problem

size() get the number of data
capacity() gets the capacity size
empty() determines whether it is empty
void resize (size_type n, value_type val = value_type()); Change the size of the vector
void reserve (size_type n); Change vector into capacity

Under VS, capacity increases by 1.5 times and g + + by 2 times

 4.vector addition, deletion, query and modification

void push_ back (const value_type& val); Tail insertion
void pop_back(); Tail deletion

void clear(); Clear
iterator insert (iterator position, const value_type& val); Insert Val before position
iterator erase (iterator position); Delete data at position
void swap (vector& x); Exchange the data space of two vectors
reference operator[] (size_type n); Access like an array

InputIterator find (InputIterator first, InputIterator last, const T& val);

Find. (note that this is an algorithm module implementation, not a member interface of vector)

Use of tail insertion and tail deletion

#include <iostream>
#include <vector>
using namespace std;

int main()
{
	int a[] = { 1, 2, 3, 4 };
	vector<int> v(a, a + sizeof(a) / sizeof(int));//The number of sizeof(a) / sizeof(int) elements. A is the first address, followed by the last address. Use the iterator to initialize the construction
//Traverse the elements printed v
//iterator is the pointer inside the int array
	vector<int>::iterator it = v.begin();//Declare and initialize the iterator it, pointing to the location of the first element of the v container
	while (it != v.end())//Determine whether it is equal to the next position of the last data
	{
		cout << *it << "";
		it++;
	}
	cout << endl;
	v.pop_back();//Tail deletion
	v.pop_back();
	v.push_back(5);//Tail insertion
//Traverse the elements printed v
	it = v.begin();
	while (it != v.end())
	{
		cout << *it << "";
		++it;
	}
	cout << endl;
	system("pause");
	return 0;
}
//Results: initial 1234, final 125

Use find to find, insert, and erase to delete interfaces

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
	int a[] = { 1, 2, 3, 4 };
	vector<int>v(a, a + sizeof(a) / sizeof(int));
	vector<int>::iterator pos = find(v.begin(), v.end(), 3);//find finds the iterator where element 3 is located
	v.insert(pos, 30);//Insert 30 before pos
	vector<int>::iterator it = v.begin();//Traverse the elements printed v
	while (it != v.end())
	{
		cout << *it << "";
		++it;
	}
	cout << endl;

	pos = find(v.begin(), v.end(), 3);
	v.erase(pos);//Delete pos location data
	it = v.begin();//Traverse the elements printed v
	while (it != v.end())
	{
		cout << *it << "";
		++it;
	}
	cout << endl;
	system("pause");
	return 0;
}
//Results: after insertion: 123034, after deletion: 12304

II. list:

The bottom layer of list is a two-way linked list structure. It is a sequential container that can be inserted and deleted at any position within the constant range, and the container can iterate back and forth.

1.list constructor

list() construct an empty list
list (size_type n, const value_type& val = value_type())

 

The constructed list contains n elements with value val
List (const list & x) copy constructor
list (InputIterator first, InputIterator last) constructs a list with elements in the [first, last) interval

 2.list iterator use

begin() returns the iterator of the first element
end() returns the iterator at the next position of the last element
rbegin() returns the reverse of the first element_ Iterator, i.e. end position, reverse
rend() returns the reverse of the next position of the last element_ Iterator, i.e. begin position
cbegin() (C++11) returns the cosnt of the first element_ iterator
cend() (C++11) returns const at the next position of the last element_ iterator
crbegin() (C++11) is the crend() position. The element value in the node cannot be modified
crend() (C++11), i.e. crbegin(), the element value in the node cannot be modified

Use of list constructor, iterator iterator and traversal printing method

#include <iostream>
#include <list>
#include <algorithm>
using namespace std;


int main()
{
	list<int> l1;//Construct an empty list
	list<int> l2(3, 10);//The constructed list contains three elements with a value of 10
	list<int> l3(l2.begin(), l2.end());//Construct a list of elements in the (first, last) interval
	list<int> l4(l3);//l4 copy structure l3

	//Construct l5 with array as iterator interval
	int array[] = { 2, 5, 10, 99 };
	list<int>l5(array, array + sizeof(array) / sizeof(int));

	//Iterates over print l5 elements
	list<int>::iterator it = l5.begin();
	for (l5.begin(); it != l5.end();it++)
	{
		cout << *it << "";
	}
	cout << endl;

	//Traverse print l5 elements in an auto for loop
	for (auto& e : l5)
	{
		cout << e << "";
	}
	cout << endl;
	system("pause");
	return 0;
}
//Result: 251099

3.list capacity

bool empty() const , check whether the list is empty. If yes, it returns true; otherwise, it returns false
size_t size() const = returns the number of valid nodes in the list

 4.list element access

reference front() returns the reference of the value in the first node of the list
const_reference front() const returns the const reference of the value in the first node of the list
reference back() returns the reference of the value in the last node of the list
const_reference back() const returns the const reference of the value in the last node of the list

The use of the above interfaces is as follows:

#include <iostream>
#include <list>
#include <algorithm>
using namespace std;


int main()
{
	int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

	list<int> l1(array, array + sizeof(array) / sizeof(array[0]));

	for (auto& e : l1)
	{
		cout << e << "";
	}
	cout << endl;

	l1.front() = 10;//Change the value of the first node in the list to 10
	l1.back() = 10;//Change the value of the last node in the list to 10
	for (auto& e : l1)
	{
		cout << e << "";
	}
	cout << endl;

	list<int>l2(array, array + sizeof(array) / sizeof(array[0]));
	const int& a = l2.front();//Const returns the const reference of the value in the first node of the list
	system("pause");
	return 0;
}
//Result: 123456789 10234567810

5.list modifiers

void push_ Front (const value_type & val) inserts an element with value val before the first element of the list
void pop_front() deletes the first element in the list
void push_ Back (const value_type & val) inserts an element with value val at the end of the list
void pop_back() deletes the last element in the list
template <class... Args>                                                                      
void emplace_ Front (args & &... Args) (C+11) constructs the element directly according to the parameters before the first element of the list
template <class... Args>                                                                      
void emplace_ Back (args & &... Args) (C+11) constructs the element according to the parameters after the last element in the list
template <class... Args>                                                                      
iterator emplace( const_iterator position, Args&&... args) 

(C++11) directly construct elements according to parameters at any position of the linked list
iterator insert (iterator position, const value_type& val)

Insert the element with value val in the position of list
void insert (iterator position, size_type n, const value_type& val)
Insert n elements with value val in the position of list
void insert (iterator position, InputIterator first, InputIterator last)
Insert the element in the [first, last) interval at the position of the list
iterator erase (iterator position) deletes the element at the list position
iterator erase (iterator first, iterator last) deletes the elements in the [first, last) interval in the list
Void swap (list & x) exchanges elements in two lists
void resize (size_type n, value_type val = value_type())
Change the number of valid elements in the list to n, and fill the extra elements with val
void clear() clears the list of valid elements

#include <iostream>
#include <list>
#include <algorithm>
using namespace std;

void PrintfList(list<int>&l)//Pass reference
{
	for (auto& e : l)
	{
		cout << e << "";
	}
	cout << endl;
}

void TestList()
{
	int array[] = { 3,2,1 };
	list<int>L(array, array + sizeof(array) / sizeof(array[0]));
	//list tail insertion
	L.push_front(4);
	L.push_back(0);
	PrintfList(L);
	//Delete the tail node and head node of the list
	L.pop_front();
	L.pop_back();
	PrintfList(L);
}
int main()
{
	TestList();
	system("pause");
	return 0;
}
//Result: 43210 321

6. Use the list modifications interface:

#include <iostream>
#include <list>
#include <vector>
#include <algorithm>
using namespace std;

void PrintfList(list<int>&l)//Pass reference
{
	for (auto& e : l)
	{
		cout << e << "";
	}
	cout << endl;
}

void TestList()
{
	int array[] = { 3,2,1 };
	list<int>L(array, array + sizeof(array) / sizeof(array[0]));
	//Get the second node in the linked list
	auto pos = ++L.begin();
	cout << *pos << endl;
	//Insert an element with a value of 4 before pos
	L.insert(pos, 4);
	PrintfList(L);
	//Insert five elements with a value of 6 before pos
	L.insert(pos, 5, 6);
	PrintfList(L);
	//Insert elements in the [v.begin(),v.end()) interval before pos
	vector<int>v { 7, 8, 9 };
	L.insert(pos, v.begin(), v.end());
	PrintfList(L);
	//Delete element at pos position
	L.erase(pos);
	PrintfList(L);
	//Delete the elements in the [begin,end) interval in the list, and delete all the elements in the list
	L.erase(L.begin(), L.end());
	PrintfList(L);
	//Change the number of elements in the list
	L.resize(15);
	PrintfList(L);
	//Increase the number of elements in L to 20, and the extra elements are filled with 4
	L.resize(20,4);
	PrintfList(L);
	//Reduce the number of elements in L to 5
	L.resize(5);
	PrintfList(L);
	//Constructing list with elements in vector
	vector<int> v1{ 7, 8, 9 };
	list<int> L1(v1.begin(), v1.end());
	PrintfList(L1);
	//Swap L and L1 elements
	L.swap(L1);
	PrintfList(L);
	PrintfList(L1);
	//Empty elements in L1
	L1.clear();
	cout << L1.size() << endl;
}
int main()
{
	TestList();
	system("pause");
	return 0;
}
//Result: 43210 321

7.list iterator failure:

Iterators are similar to pointers. The underlying structure of the list is a two-way circular linked list of the leading node. They will only fail when deleted, and only the iterators pointing to the deleted node will fail, and other iterators will not be affected.

8. The difference between vector and list:

vectorvectorlist

Bottom structure

Dynamic sequence table, a continuous spaceBidirectional circular linked list of leading nodes
Random accessSupport random access to access an element. Efficiency O(1)Random access is not supported to access an element
Efficiency O(N)
Insert deleteThe efficiency of inserting and deleting at any position is low, the elements need to be moved, and the time is complex
When the degree is O(N), it may be necessary to increase the capacity during insertion. Capacity increase: open up a new space
Between, copy elements to free up old space, resulting in lower efficiency
The insertion and deletion at any position is efficient and does not need to be deleted
Elements need to be moved. The time complexity is
O(1)
Space utilizationThe bottom layer is continuous space, which is not easy to cause memory fragmentation and space utilization
High cache utilization
The bottom node is opened dynamically, and the subsection is easy
Causing memory fragmentation and low space utilization,
Low cache utilization
iterator Original ecological indicatorEncapsulate the original ecological pointer (node pointer)
Iterator failureWhen inserting an element, all iterators need to be reassigned because of the insertion
Element may lead to re expansion, invalidation of the original iterator and deletion
In addition, the current iterator needs to be re assigned, otherwise it will become invalid
Inserting elements does not invalidate the iterator,
Deleting an element will only result in the current iteration
The iterator fails and other iterators are not affected
Usage scenarioIt requires efficient storage, supports random access, and does not care about the efficiency of insertion and deletionA large number of insert and delete operations, do not care with
Machine access

Topics: C++