[C++ container] vector (2)

1. Basic concepts of vector

Features:

  • The vector data structure is very similar to an array , also known as a single-ended array

The difference between vector and ordinary array:

  • The difference is that the array is a static space, while the vector can be dynamically expanded

Dynamic expansion:

  • It is not to connect the new space after the original space, but to find a larger memory space , and then copy the original data to the new space to release the original space

Vector operations front() and back() , push_back() and pop_back , v.begin() and v.end() , v.rend() and v.rbegin() , insert()

The iterator of the vector container is an iterator that supports random access

2. Vector constructor

Function description:

  • Create a vector container

Function prototype:

  • vector<T> v; //Using template implementation class implementation, default constructor

  • vector(v.begin(), v.end()); //Copy the elements in the range of v[begin(), end()) to itself.

  • vector(n, elem); //The constructor copies n elems to itself.

  • vector(const vector &vec); //Copy constructor.

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


/*

vector<T> v;                	//采用模板实现类实现,默认构造函数
vector(v.begin(), v.end());     //将v[begin(), end())区间中的元素拷贝给本身。
vector(n, elem);                //构造函数将n个elem拷贝给本身。
vector(const vector &vec);      //拷贝构造函数。

*/

void printVector1(vector<int>v)
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << (*it) << "\t";
	}
	cout << endl;
}

void test01()
{
	//第一种  默认构造,无参构造
	vector<int>v1;
	//赋值
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i);
	}
	//打印
	printVector1(v1);

	//第二种 通过区间的方式构造
	vector<int>v2(v1.begin(), v1.end());
	printVector1(v2);

	//第三种
	vector<int>v3(10, 100);   //10个100
	printVector1(v3);

	//第四种 拷贝构造
	vector<int>v4(v3);
	printVector1(v4);
}

int main(void)
{
	test01();
	system("pause");
	return 0;
}

3. Vector assignment operation

Function description:

  • Assign a value to the vector container

Function prototype:

  • vector& operator=(const vector &vec);//Overload the equal sign operator

  • assign(beg, end); // Assign a copy of the data in the interval [beg, end) to itself.

  • assign(n, elem); //Assign n copies of elem to itself.

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


/*

vector& operator=(const vector &vec); //重载等号操作符

assign(beg, end);                     //将[beg, end)区间中的数据拷贝赋值给本身。
assign(n, elem);                      //将n个elem拷贝赋值给本身。

*/

//打印函数
void printVector2(vector<int>&v)
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << (*it) << "\t";
	}
	cout << endl;
}

void test02()
{
	vector<int>v1;
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i);
	}
	printVector2(v1);

	//第一种 等号赋值
	vector<int>v2;
	v2 = v1;
	printVector2(v2);

	//第一种 assign
	vector<int>v3;
	v3.assign(v1.begin(), v1.end());
	printVector2(v3);

	//第三种
	vector<int>v4;
	v4.assign(10, 100);
	printVector2(v4);


}

int main(void)
{
	test02();
	system("pause");
	return 0;
}

4. Vector capacity and size

Function description:

  • Operations on the capacity and size of the vector container

Function prototype:

  • empty();                                           //Determine whether the container is empty

  • capacity();                                     //The capacity of the container

  • size();                                            //Returns the number of elements in the container

  • resize(int num);                            //Re-specify the length of the container as num. If the container becomes longer, the new position will be filled with the default value. If the container becomes shorter, the elements at the end that exceed the length of the container are deleted.

  • resize(int num, elem);      //Re-specify the length of the container as num. If the container becomes longer, fill the new position with the elem value. If the container becomes shorter, the elements at the end that exceed the length of the container are deleted

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

/*
empty();                     //判断容器是否为空
capacity();                  //容器的容量
size();                      //返回容器中元素的个数
resize(int num);             //重新指定容器的长度为num,若容器变长,则以默认值填充新位置。
                             //如果容器变短,则末尾超出容器长度的元素被删除。
resize(int num, elem);       //重新指定容器的长度为num,若容器变长,则以elem值填充新位置。
                             //如果容器变短,则末尾超出容器长度的元素被删除
*/

//打印函数
void printVector3(vector<int>&v)
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << (*it) << "\t";
	}
	cout << endl;
}

void test03()
{
	vector<int>v1;
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i);
	}
	printVector3(v1);

	//判断是否为空
	if (v1.empty())
	{
		cout << "v1为空" << endl;
	}
	else
	{
		cout << "v1不为空" << endl;
		cout << "v1的容量 " << v1.capacity() << endl;   //13
		cout << "v1的大小 " << v1.size() << endl;       //10
	}

	//重新指定大小
	v1.resize(15);   
	printVector3(v1);     //如果指定的比原来常,默认补充0

	v1.resize(20, 100);    //用100填充
	printVector3(v1);     //如果指定的比原来常,补充100

	//比原来短
	v1.resize(5);
	printVector3(v1);     //如果容器变短,则末尾超出容器长度的元素被删除

}

int main(void)
{
	test03();
	system("pause");
	return 0;
}

to sum up:

  • Determine whether it is empty --- empty

  • Return the number of elements --- size

  • Return container capacity --- capacity

  • Re-specify the size --- resize

5. Vector insertion and deletion

Function description:

  • Insert and delete the vector container

Function prototype:

  • push_back(ele); //Insert element ele at the end

  • pop_back(); //Delete the last element

  • insert(const_iterator pos, ele); //The iterator points to the position pos to insert the element ele

  • insert(const_iterator pos, int count,ele);//The iterator points to the position pos and inserts count elements ele

  • erase(const_iterator pos); //Delete the element pointed to by the iterator

  • erase(const_iterator start, const_iterator end);//Delete the elements between start and end of the iterator

  • clear(); //Delete all elements in the container

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

/*

push_back(ele);                                         //尾部插入元素ele
pop_back();                                             //删除最后一个元素
insert(const_iterator pos, ele);                        //迭代器指向位置pos插入元素ele
insert(const_iterator pos, int count,ele);              //迭代器指向位置pos插入count个元素ele
erase(const_iterator pos);                              //删除迭代器指向的元素
erase(const_iterator start, const_iterator end);        //删除迭代器从start到end之间的元素
clear();                                                /删除容器中所有元素

*/
//打印函数
void printVector4(vector<int>&v)
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << (*it) << "\t";
	}
	cout << endl;
}

void test04()
{
	vector<int>v1;
	//利用尾插法插入数据
	v1.push_back(10);
	v1.push_back(20);
	v1.push_back(30);
	v1.push_back(40);
	v1.push_back(50);

	//打印
	printVector4(v1);

	//尾删
	v1.pop_back();

	//打印
	printVector4(v1);

	//插入 提供迭代器插入
	v1.insert(v1.begin(), 100);
	printVector4(v1);

	v1.insert(v1.begin(), 2, 1000);    //插入2个1000
	printVector4(v1);

	//删除
	v1.erase(v1.begin());     //参数也是迭代器
	printVector4(v1); 

	//v1.erase(v1.begin(), v1.end());    //清空
	v1.clear();
	printVector4(v1);

}


int main(void)
{
	test04();
	system("pause");
	return 0;
}

to sum up:

  • End plug --- push_back

  • End delete --- pop_back

  • Insert --- insert (position iterator)

  • Delete --- erase (position iterator)

  • Clear--- clear

6, vector data access

Function description:

  • Access operations on the data in the vector

Function prototype:

  • at(int idx); //Return the data pointed to by the index idx

  • operator[]; //Return the data pointed to by the index idx

  • front(); //Return the first data element in the container

  • back(); //Return to the last data element in the container

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

/*
at(int idx);      //返回索引idx所指的数据
operator[];       //返回索引idx所指的数据
front();          //返回容器中第一个数据元素
back();           //返回容器中最后一个数据元素

*/


void test05()
{
	vector<int>v1;
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i);
	}

	//利用中括号
	for (int i = 0; i < v1.size(); i++)
	{
		cout << v1[i] << "\t";    
	}
	cout << endl;

	//利用at()
	for (int i = 0; i < v1.size(); i++)
	{
		cout << v1.at(i)<< "\t";     
	}
	cout << endl;

	//获取第一个元素
	cout << "第一个元素是" << v1.front() << endl;
	cout << "最后一个元素是" << v1.back() << endl;

}

int main(void)
{
	test05();
	system("pause");
	return 0;
}

to sum up:

  • In addition to using iterators to get the elements in the vector container, [] and at can also be used

  • front returns the first element of the container

  • back returns the last element of the container

7, vector interchange container

Function description:

  • Realize the exchange of elements in the two containers

Function prototype:

  • swap(vec); // Exchange vec with its own elements

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

//打印函数
void printVector6(vector<int>&v)
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << (*it) << "\t";
	}
	cout << endl;
}

//1、基本使用
void test06()
{
	vector<int>v1;
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i);
	}
	cout << "交换前的打印:" << endl;
	printVector6(v1);

	vector<int>v2;
	for (int i = 10; i > 0; i--)
	{
		v2.push_back(i);
	}
	printVector6(v2);

	cout << "交换后的打印:" << endl;
	v1.swap(v2);
	printVector6(v1);
	printVector6(v2);
}

//2、实际用途  收缩内存空间
void test006()
{
	vector<int> v;
	for (int i = 0; i < 100000; i++)
	{
		v.push_back(i);
	}
	cout << "v的容量是:" << v.capacity() << endl;    //138255
	cout << "v的大小是:" << v.size() << endl;        //100000

	v.resize(3);      //重新指定大小
	cout << "v的容量是:" << v.capacity() << endl;    //138255
	cout << "v的大小是:" << v.size() << endl;        //3

	//浪费空间
	//巧用swap收缩内存
	vector<int>(v).swap(v);
	//vector<int>(v)匿名对象,按照v来初始化,用v所用的大小来初始化,再交换,系统会回收匿名对象

	cout << "v的容量是:" << v.capacity() << endl;    //3
	cout << "v的大小是:" << v.size() << endl;        //3
}

int main(void)
{
	test06();
	test006();
	system("pause");
	return 0;
}

Summary: swap can interchange two containers, which can achieve practical memory shrinkage effects    

8, vector reserved space

Function description:

  • Reduce the number of expansions of vector when dynamically expanding capacity

Function prototype:

  • reserve(int len);//The container reserves len element lengths, the reserved position is not initialized, and the elements are inaccessible.

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

void test08()
{
	vector<int> v;

	int num = 0;          //统计开辟的次数
	int* p = NULL;        //因为每次扩容是重新开辟空间,所以第二次时,p指向的首地址不再是扩容后的首地址,判断成立,计数器自加
	for (int i = 0; i < 100000; i++)
	{
		v.push_back(i);
		if (p != &v[0])
		{
			p = &v[0];
			num++;
		}
	}
	cout << "num = " << num << endl;

}

int main(void)
{
	test08();
	system("pause");
	return 0;
}

30 times opened up

Use reserve to reserve space

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

void test08()
{
	vector<int> v;

	//利用reserve预留空间
	v.reserve(100000);
	int num = 0;          //统计开辟的次数
	int* p = NULL;        //因为每次扩容是重新开辟空间,所以第二次时,p指向的首地址不再是扩容后的首地址,判断成立,计数器自加
	for (int i = 0; i < 100000; i++)
	{
		v.push_back(i);
		if (p != &v[0])
		{
			p = &v[0];
			num++;
		}
	}
	cout << "num = " << num << endl;

}

int main(void)
{
	test08();
	system("pause");
	return 0;
}

Summary: If the amount of data is large, you can use reserve to reserve space at the beginning

Guess you like

Origin blog.csdn.net/Zhouzi_heng/article/details/115124490