C++—the use of vector

First, the introduction of vector

To put it simply:
vector is an array container that can grow dynamically

  1. vectoris a sequence container representing a variable-sized array.
  2. Just like an array, vectorit also uses a contiguous storage space to store elements. That is, it means that the elements of the subscript pair can vectorbe accessed, just as efficiently as an array.
  3. Essentially, vectoruse a dynamically allocated array to store its elements. When new elements are inserted, the array needs to be resized to increase storage space.
  4. vectorAllocation space policy: vectorSome extra space is allocated to accommodate possible growth, as the storage space is larger than is actually needed. .
  5. Therefore, vectormore storage space is occupied, in order to gain the ability to manage storage space and grow dynamically in an efficient manner.
  6. Compared to other dynamic sequence containers ( deques, lists and forward_lists), vectors are more efficient at accessing elements, and adding and removing elements at the end is relatively efficient. For other delete and insert operations that are not at the end, it is less efficient. Better than listsand forward_listsunified iterators and references.

If you want to know more , please click here

Second, the use of vector

2.1 vector constructor

Constructor Features
vector() No-argument constructor
vector(size_type n, const value_type& val = value_type()) Construct and initialize n vals
vector (const vector& x)( emphasis ) copy construction
vector (InputIterator fifirst, InputIterator last) Initialize construction with iterators
void test1()
{
    
    
	vector<int> v1;//无参的构造用的最多
	vector<int> v2(10,1);//用10个1来初始化
	vector<int> v3(v2.begin(),v2.end());//用一段迭代器区间去初始化
	vector<int> v4(v3);//拷贝构造

	string s("hello");
	vector<char> v5(s.begin(), s.end());//不同STL的迭代器区间也可以初始化
}

Result display:
Open the monitoring window to observe, it is indeed initialized
insert image description here
question:
for the following cases:

string s; 和 vector<char> v; 

Is it about the same? Can they replace each other?

 No way! Because the string is carried at the end \0, and the string provides some special string-related interface functions, such as: operator+=, c_str, find and other functions

2.2 The use of iterators

use of iterator Features
begin+end Get the iterator/const_iterator of the first data position, get the iterator/const_iterator of the next position of the last data
rebegin+rend Get the reverse_iterator of the last data position, get the reverse_iterator of the previous position of the first data

insert image description here

//vector中如何遍历
void test2()
{
    
    
	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);
	v.push_back(4);

	//下标[]遍历
	for (size_t i = 0; i < v.size(); ++i)
	{
    
    
		v[i] += 1;
		cout << v[i] << " ";
	}
	cout << endl;

	//迭代器
	vector<int>::iterator it=v.begin();
	while (it != v.end())
	{
    
    
		
		cout << *it << " ";
		++it;
	}
	cout << endl;
	
	//反向迭代器
   	vector<int>::reverse_iterator rit = v.rbegin();
	while (rit != v.rend())
	{
    
    
		cout << *rit << " ";
		++rit;
	}
	//范围for
	for (auto e : v)
	{
    
    
		cout << e << " ";
	}
	cout << endl;
}

2.3 The problem of space growth

capacity function Features
size( ) Get the number of data
capacity( ) Get capacity size
empty( ) Empty
resize( ) change size
reserve( ) change capacity
void test3()
{
    
    
	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);
	v.push_back(4);

	cout << v.size() << endl;
	cout << v.capacity() << endl;
	cout << v.empty() << endl;
	cout << endl;

	v.reserve(100);//改变capacity
	cout << v.size() << endl;
	cout << v.capacity() << endl;
	cout << v.empty() << endl;
	cout << endl;

	v.resize(10,1);//改变size,默认给上缺省值0,它可以 扩容+初始化 或者 删除数据
	cout << v.size() << endl;
	cout << v.capacity() << endl;
	cout << v.empty() << endl;
	cout << endl;

	v.resize(2);
	cout << v.size() << endl;
	cout << v.capacity() << endl;
	cout << v.empty() << endl;
	cout << endl;
}

Results show:
insert image description here
Summarize

  • When the capacity code is run under vs and g++ respectively, it will be found that under vs, capacity increases by 1.5 times, and g++ increases by 2 times. This question is often investigated. Don't think that the sequence table is doubled in capacity, and the specific increase is defined according to specific needs. vs is the PJ version STL, g++ is the SGI version STL.
  • Reserve is only responsible for opening up space. If you know how much space you need to use, reserve can alleviate the cost defect of vector expansion.
  • Resize will also be initialized when opening space, affecting size.

2.4 The problem of adding, deleting, checking and modifying

function Features
push_back( ) tail plug
pop_back( ) tail deletion
insert( ) insert before pos
erase( ) delete
swap( ) Swap the data space of two vectors
operator[ ]常用 Subscript location access
find( ) This is the lookup ( ) implemented in the algorithm library algorithm, not a member function of vector
void test4()
{
    
    
	vector<int> v;
	//push_back尾插
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);
	v.push_back(4);
	
	//find查找
	vector<int>::iterator ret = find(v.begin(), v.end(),3);
	auto ret1 = find(v.begin(), v.end(), 3);
	//可以用auto替换
	if (ret != v.end())
	{
    
    
		cout << "找到了" << endl;
	}
	v.insert(ret, 100);
	for (auto e : v)
	{
    
    
		cout << e << " ";
	}

	vector<int>::iterator pos = find(v.begin(), v.end(), 1);
	if (pos != v.end())//判断数据是否合法
	{
    
    
		//erase删除
		v.erase(pos);
	}
	cout << endl;
}

Result demonstration:
insert image description here
operator[ ] and range for are common traversal methods in vector

// vector使用这两种遍历方式是比较便捷的。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    
    
	int a[] = {
    
     1, 2, 3, 4 };
	vector<int> v(a, a + sizeof(a) / sizeof(int));

	// 通过[]读写第0个位置。
	v[0] = 10;
	cout << v[0] << endl;

	// 通过[i]的方式遍历vector
	for (size_t i = 0; i < v.size(); ++i)
		cout << v[i] << " ";
	cout << endl;

	vector<int> swapv;
	swapv.swap(v);
	cout << "v data:";
	for (size_t i = 0; i < v.size(); ++i)
		cout << v[i] << " ";
	cout << endl;

	cout << "swapv data:";
	for (size_t i = 0; i < swapv.size(); ++i)
		cout << swapv[i] << " ";
	cout << endl;

	// C++11支持的新式范围for遍历
	for (auto x : v)
		cout << x << " ";
	cout << endl;
	return 0;
}

illustrate: vector supports iterators, and you can also use range for to traverse the vector. Support for iterators supports range for, because the compiler will automatically replace range for with iterator traversal at compile time.

Guess you like

Origin blog.csdn.net/weixin_57675461/article/details/123960637