C++ STL vector use detailed explanation

I. Overview

Vector (vector): It is a serial container, which is similar to an array in fact, but it is superior to an array. Generally speaking, the array cannot be expanded dynamically, so when the program is running, it either wastes memory or causes out-of-bounds. And vector just makes up for this defect. Its feature is that it is equivalent to an array that can be allocated and expanded (dynamic array). Its random access is fast, insertion and deletion in the middle are slow, but insertion and deletion at the end are fast.

2. Definition and initialization

The header file of the corresponding container must be added before use:

#include <vector> // vector属于std命名域的,因此需要通过命名限定,例如using std::vector;

The defined implementation code is as follows:

vector<int> a; // 定义一个int类型的向量a
vector<int> a(10); // 定义一个int类型的向量a,并设置初始大小为10
vector<int> a(10, 1); // 定义一个int类型的向量a,并设置初始大小为10且初始值都为1
vector<int> b(a); // 定义并用向量a初始化向量b
vector<int> b(a.begin(), a.begin()+3); // 将a向量中从第0个到第2个(共3个)作为向量b的初始值

In addition, you can also use arrays directly to initialize vectors:

int n[] = {1, 2, 3, 4, 5} ;
// 将数组n的前5个元素作为向量a的初值
// 说明:当然不包括arr[4]元素,末尾指针都是指结束元素的下一个元素
// 这个主要是为了和vec.end()指针统一。
vector<int> a(n, n+5) ;              
vector<int> a(&n[1], &n[4]) ;        // 将n[1]、n[2]、n[3]作为向量a的初值

3. Basic operation functions

3.1 Capacity function

  • Container size: vec.size();
  • Container capacity: vec.capacity(); // refers to the maximum number of elements that can be allowed before realloc occurs, that is, the pre-allocated memory space, which is different from size()
  • The maximum capacity of the container: vec.max_size();
  • Change container size: vec.resize();
  • The container is empty: vec.empty();
#include <iostream>
#include <vector>

using namespace std;

int main(int argc, char* argv[])
{
	vector<int> vec;
	for (int i = 0; i<6; i++)
	{
		vec.push_back(i);
	}

	cout << vec.size() << endl; // 输出:6
	cout << vec.capacity() << endl; // 输出:6
	cout << vec.max_size() << endl; // 输出:1073741823
	vec.resize(0);
	cout << vec.size() << endl; // 输出:0
	if (vec.empty())
		cout << "元素为空" << endl; // 输出:元素为空

	return 0;
}

Note: vec.resize(10) will assign 10 0s to vec, which is equivalent to push_back(0) 10 times.

3.2 Add function

  • Add elements at the end: vec.push_back(const T& x);
  • Insert an element at any position: vec.insert(iterator it, const T& x);
  • Insert n identical elements at any position: vec.insert(iterator it, int n, const T& x);
  • Insert data between [forst, last] of another vector: vec.insert(iterator it, iterator first, iterator last);
#include <iostream>
#include <vector>

using namespace std;

int main(int argc, char* argv[])
{
	vector<int> vec;

	// 末尾添加元素
	vec.push_back(5);
	// 任意位置插入一个元素
	vector<int>::iterator it = vec.begin();
	vec.insert(it, 2);
	// 任意位置插入n个相同元素
	it = vec.begin();
	vec.insert(it, 3, 9);
	// 插入另一个向量的[forst,last]间的数据
	vector<int> vec2(5, 8);
	it = vec.begin();
	vec.insert(it, vec2.end() - 1, vec2.end());

	// 遍历显示
	for (it = vec.begin(); it != vec.end(); it++)
		cout << *it << " "; // 输出:8 9 9 9 2 5
	cout << endl;

	return 0;
}

3.3 Delete function

  • Delete elements at the end: vec.pop_back();
  • Delete an element anywhere: vec.erase(iterator it);
  • Delete elements between [first, last]: vec.erase(iterator first, iterator last);
  • Clear all elements: vec.clear();
#include <iostream>
#include <vector>

using namespace std;

int main(int argc, char* argv[])
{
	vector<int> vec;
	for (int i = 0; i < 8; i++)
		vec.push_back(i);

	// 末尾删除元素
	vec.pop_back();
	// 任意位置删除一个元素
	vector<int>::iterator it = vec.begin();
	vec.erase(it);
	// 删除[first,last]之间的元素
	vec.erase(vec.begin(), vec.begin() + 1);

	for (it = vec.begin(); it != vec.end(); it++)
		cout << *it << " ";
	cout << endl;

	// 清空所有元素
	vec.clear();

	// 遍历显示   
	for (it = vec.begin(); it != vec.end(); it++)
		cout << *it << " "; // 输出:2 3 4 5 6
	cout << endl;

	return 0;
}

3.4 Access functions

  • Subscript access: vec[1]; // does not check whether it is out of bounds
  • at method access: vec.at(1); // The difference between the above two is that at will check whether it is out of range, and if so, throw an out of range exception
  • Access the first element: vec.front();
  • Access the last element: vec.back();
  • Return a pointer: int* p = vec.data(); // The reason why it is feasible is that vector is an array of continuous storage in memory, so a pointer can be returned to point to this array. This is a feature of C++11.
#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;

int main(int argc, char* argv[])
{
	vector<int> vec;
	for (int i = 0; i < 6; i++)
		vec.push_back(i);

	// 下标访问
	cout << vec[0] << endl; // 输出:0
	// at方法访问
	cout << vec.at(0) << endl; // 输出:0
	// 访问第一个元素
	cout << vec.front() << endl; // 输出:0
	// 访问最后一个元素
	cout << vec.back() << endl; // 输出:5
	// 返回一个指针
	int *p = vec.data();
	cout << *p <<endl; // 输出:0

	return 0;
}

3.5 Other functions

  • Assignment of multiple elements: vec.assign(int nSize, const T& x); // similar to using an array for assignment during initialization
  • Exchange the elements of two containers of the same type: swap(vector&);
#include <iostream>
#include <vector>

using namespace std;

int main(int argc, char* argv[])
{
	// 多个元素赋值
	vector<int> vec;
	vec.assign(3, 1);
	vector<int> vec2;
	vec2.assign(3, 2);

	// 交换两个容器的元素
	vec.swap(vec2);

	// 遍历显示
	cout << "vec: ";
	for (int i = 0; i < vec.size(); i++)
		cout << vec[i] << " "; // 输出:2 2 2
	cout << endl;

	// 遍历显示
	cout << "vec2: ";
	for (int i = 0; i < vec2.size(); i++)
		cout << vec2[i] << " "; // 输出:1 1 1
	cout << endl;

	return 0;
}

4. Iterators and Algorithms

1. Iterators

  • Start pointer: vec.begin();
  • End pointer: vec.end(); // point to the next position of the last element
  • Pointer to the beginning of the constant: vec.cbegin(); // It means that the pointed content cannot be modified through this pointer, but it can still be modified in other ways, and the pointer can also be moved.
  • Pointer to the end of the constant: vec.cend();
#include <iostream>
#include <vector>

using namespace std;

int main(int argc, char* argv[])
{
	vector<int> vec;
	vec.push_back(1);
	vec.push_back(2);
	vec.push_back(3);

	cout << *(vec.begin()) << endl; // 输出:1
	cout << *(--vec.end()) << endl; // 输出:3
	cout << *(vec.cbegin()) << endl; // 输出:1
	cout << *(--vec.cend()) << endl; // 输出:3
	cout << *(vec.rbegin()) << endl; // 输出:3
	cout << *(--vec.rend()) << endl; // 输出:1
	cout << endl;

	return 0;
}

2. Algorithms

  • traverse elements
vector<int>::iterator it;
for (it = vec.begin(); it != vec.end(); it++)
    cout << *it << endl;
// 或者
for (int i = 0; i < vec.size(); i++) {
    cout << vec.at(i) << endl;
}
  • element flip
#include <algorithm>
reverse(vec.begin(), vec.end());
  • element sorting
#include <algorithm>
sort(vec.begin(), vec.end()); // 采用的是从小到大的排序

// 如果想从大到小排序,可以采用先排序后反转的方式,也可以采用下面方法:
// 自定义从大到小的比较器,用来改变排序方式
bool Comp(const int& a, const int& b) 
{
    return a > b;
}

sort(vec.begin(), vec.end(), Comp);

Guess you like

Origin blog.csdn.net/QtCompany/article/details/131710272