6 STL-vector

 重新系统学习c++语言,并将学习过程中的知识在这里抄录、总结、沉淀。同时希望对刷到的朋友有所帮助,一起加油哦!

 

 生命就像一朵花,要拼尽全力绽放!死磕自个儿,身心愉悦!

写在前面,本篇章主要介绍STL中常用容器vector。

1.1 vector的基本概念

vector数据结构和数组非常相似,也称为单端数组。

vector与普通数组的区别:

        数组是静态空间,而vector可以自动动态扩展空间。

什么叫动态扩展?

  • 并不是在原空间后继续增大新空间
  • 而是找大更大的内存空间,然后将原数据拷贝到新空间,并释放原空间。

vector特点:

  1. 前端封闭,不能进行插入和删除,通常在尾部进行插入和删除。push_back()插入,pop_back()删除。
  2. v.begin()指向第一个元素位置,v.end()指向最后一个元素的下一个位置。
  3. v.rbegin()指向倒数第一个元素位置,v.rend()指向一个元素的前一个位置。
  4. 还提供很多其他接口,例如插入insert()、erase()删除等。
  5. 迭代器支持随机访问。可跳跃式访问,例如 it 指向迭代器,可以加n。

编辑

 

1.2 vector构造函数

函数原型:

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

示例:


#include <iostream>
#include <string>
#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 printVector(vector<int>& v) {
	for (int item : v) {
		cout << item << " ";
	}
	cout << endl;
}

void test() {
	vector<int> v1;
	for (int i = 1; i < 6; i++) {
		v1.push_back(i);
	}

	printVector(v1);

	vector<int> v2(v1.begin(), v1.end());
	// 用区间的方式来构造vector,只要传入的是一个区间就可以拷贝区间内的数据到新的vector
	//vector<int> v2(v1.begin(), v1.begin() + 3);
	printVector(v2);

	vector<int> v3(10,5);
	printVector(v3);

	vector<int> v4(v3);
	printVector(v4);
}

int main() {
	test();

	system("pause");
	return 0;
}

 

1.3 vector赋值操作

函数原型:

  • vector& operator=(const vector& vec);       //重载等号操作符
  • assign(beg, end);                                        //将[beg, end)区间中的数据拷贝赋值给本身。
  • assign(n, elem);                                          //将n个elem拷贝赋值给本身。

示例:


#include <iostream>
#include <string>
#include<vector>

using namespace std;

//vector& operator=(const vector& vec);	//重载等号操作符
//assign(beg, end);						//将[beg, end)区间中的数据拷贝赋值给本身。
//assign(n, elem);						//将n个elem拷贝赋值给本身。

void printVector(vector<int>& v) {
	for (int item : v) {
		cout << item << " ";
	}
	cout << endl;
}

void test() {
	vector<int> v1;
	for (int i = 1; i < 6; i++) {
		v1.push_back(i);
	}

	printVector(v1);

	//vector& operator=(const vector& vec);	//重载等号操作符
	vector<int> v2;
	v2 = v1;
	printVector(v2);

	//assign(beg, end);//将[beg, end)区间中的数据拷贝赋值给本身。
	vector<int> v3;
	v3.assign(v1.begin(), v1.end());
	printVector(v3);

	//assign(n, elem);//将n个elem拷贝赋值给本身。
	v3.assign(10, 3);
	printVector(v3);
}

int main() {
	test();

	system("pause");
	return 0;
}

 

1.4 vector容量大小

函数原型:

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

注意:

  • 若重新指定容器长度,若容器变长,则capacity()容器的容量和size()都会变长。
  •  若后续又指定容器变短,则capacity()容器的容量不变只有size()会变小
  • 只有size()可变大变小,capacity()容器的容量只会变大。

示例:


#include <iostream>
#include <string>
#include<vector>

using namespace std;

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

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

void test() {
	vector<int> v1;
	for (int i = 1; i < 6; i++) {
		v1.push_back(i);
	}
	printVector(v1);

	if (v1.empty()) {
		cout << "v1 为空" << endl;
	}
	else {
		cout << "v1 不为空" << endl;
		cout <<"capacity:"<< v1.capacity() << endl;
		cout << "size:" << v1.size() << endl;
	}

	// 手动重新指定容器长度变大为10
	v1.resize(10);
	cout << "v1 手动重新指定容器长度变大" << endl;
	cout << "capacity:" << v1.capacity() << endl; // 容量会扩展成10
	cout << "size:" << v1.size() << endl; // 元素个数会变为10
	printVector(v1); // 以默认值0填充

	// 手动重新指定容器长度变小为3
	v1.resize(3);
	cout << "v1 手动重新指定容器长度变小" << endl;
	cout << "capacity:" << v1.capacity() << endl; // ***容量不变 10
	cout << "size:" << v1.size() << endl; // 元素个数会变少 3
	printVector(v1); // 如果容器变短,则末尾超出容器长度的元素被删除。

	// resize(int num, elem);利用重载版本,指定默认值填充方式,
	v1.resize(5,10);
	cout << "v1 指定默认值填充方式" << endl;
	cout << "capacity:" << v1.capacity() << endl; // ***容量不变 10
	cout << "size:" << v1.size() << endl; // 元素个数等于指定个数5
	printVector(v1); //如果重新指定的比原来的长,用默认值填充10


}

int main() {
	test();

	system("pause");
	return 0;
}

 

1.5 vector插入和删除

函数原型:

  • 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);                                  //删除迭代器指向pos位置的元素
  • erase(const_iterator start, const_iterator end);   //删除迭代器[start,end)之间的元素,左闭右开
  • clear();                                                                //删除容器中所有元素

erase(v.begin(), v.end()); 与clear()效果一样,都是清空数据。

示例:


#include <iostream>
#include <string>
#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);						 //删除迭代器指向pos位置的元素
//erase(const_iterator start, const_iterator end); //删除迭代器从start到end之间的元素
//clear();										 //删除容器中所有元素

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

void test() {
	vector<int> v1;
	for (int i = 1; i < 6; i++) {
		v1.push_back(i);
	}
	printVector(v1);

	// 尾删
	v1.pop_back();
	printVector(v1);

	//在迭代器指向位置pos插入元素ele
	v1.insert(v1.begin() + 1, 10);
	printVector(v1);

	//insert(const_iterator pos, int count, ele);
    //在迭代器指向位置pos插入count个元素ele
	v1.insert(v1.begin() + 1,3,10);
	printVector(v1);

	//erase(const_iterator pos);//删除迭代器指向pos位置的元素
	v1.erase(v1.begin() + 1);
	printVector(v1);

	//erase(const_iterator start, const_iterator end);
    //删除迭代器从[start,end)之间的元素,左闭右开
	v1.erase(v1.begin(),v1.begin()+1);
	printVector(v1);

	//clear();//删除容器中所有元素
    //v1.erase(v1.begin(), v1.end()); 也是清空数据
	v1.clear();
	printVector(v1);
}

int main() {
	test();

	system("pause");
	return 0;
}

 

1.6 vector数据存取

函数原型:

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

示例:


#include <iostream>
#include <string>
#include<vector>

using namespace std;

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

void test() {
	vector<int> v1;
	for (int i = 1; i < 6; i++) {
		v1.push_back(i);
	}
	cout << v1.at(3) << endl;  // 第三个
	cout << v1[3]<< endl;  // 第三个
	cout << v1.front() << endl;  // 第一个
	cout << v1.back() << endl;  // 最后一个
}

int main() {
	test();

	system("pause");
	return 0;
}

 

1.7 vector互换容器

函数原型:

        swap(v);  将两个vector容器互换

实际用途:

        巧用swap可以收缩内存空间。

示例:


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

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

void test() {
	cout << "交换前:" << endl;
	vector<int> v1;
	for (int i = 0; i < 10; i++) {
		v1.push_back(i);
	}
	printVector(v1);

	vector<int> v2;
	for (int i = 9; i >=0; i--) {
		v2.push_back(i);
	}
	printVector(v2);
	
	cout << "交换后:" << endl;
	v1.swap(v2);
	printVector(v1);
	printVector(v2);
}

// 实际用途
// 巧用swap可以收缩内存空间
void test2() {
	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);  // 重新指定大小。当大小变的很小时,capacity还是占用空间很大,不会缩小
	cout << "v的容量为:" << v.capacity() << endl;  // 138255
	cout << "v的长度为:" << v.size() << endl;  // 3

	// 巧用swap收缩内存
	// vector<int>(v) 利用v示例化一个匿名对象容器。这个容器容量和长度只有3
	// swap(v) 交换匿名对象容器和v
	vector<int>(v).swap(v);
	cout << "v的容量为:" << v.capacity() << endl;  // 3
	cout << "v的长度为:" << v.size() << endl;  // 3

}

int main() {
	test2();

	system("pause");
	return 0;
}

 

1.8 vector预留空间

作用:

        减少vector动态扩展容量的次数,提升性能。

函数原型:

        reserve(int len); // 容器预留len个元素长的容量,预留位置的元素不会被初始化,元素不可访问。

使用时机:

        如果知道数据量很大,就可以先使用reserve来预留空间。

示例:


#include <iostream>
#include <string>
#include<vector>

using namespace std;

void test() {
	vector<int> v;

	// 利用预留空间
	v.reserve(100000);
	// cout << v[0] << endl; // 会报错,0位置元素不可访问,未初始化。

	int num = 0;
	int* p = NULL;
	for (int i = 0; i < 100000; i++) {
		v.push_back(i);

		if (p != &v[0]) {  // 如果v做了动态内存扩展p就不会指向&v[0] 
			p = &v[0];  // 让指针p指向v的首地址
			num++;  // 如果v做了动态内存扩展,num就增加一次
		}
	}

	cout << num << endl;
}

int main() {
	test();

	system("pause");
	return 0;
}


posted on 2022-11-24 11:34  爱学习的小灵子  阅读(26)  评论(0编辑  收藏  举报