<vector>——《C++初阶》

目录

1.vector的介绍及使用

1.1 vector的介绍

1.2 vector的使用

1.2.2 vector iterator 的使用

1.2.3 vector 空间增长问题 

 1.2.3 vector 增删查改

1.2.4 vector 迭代器失效问题。(重点)

1.2.5 vector 在OJ中的使用

 2.常用接口测试:

后记:●由于作者水平有限,文章难免存在谬误之处,敬请读者斧正,俚语成篇,恳望指教!                                                ——By 作者:新晓·故知


1.vector的介绍及使用

1.1 vector的介绍

vector的文档介绍链接:vector - C++ Reference
1. vector是表示可变大小数组的序列容器。
2. 就像数组一样,vector也采用的连续存储空间来存储元素。也就是意味着可以采用下标对vector的元素进行访问,和数组一样高效。但是又不像数组,它的大小是可以动态改变的,而且它的大小会被容器自动处理。
3. 本质讲,vector使用动态分配数组来存储它的元素。当新元素插入时候,这个数组需要被重新分配大小为了增加存储空间。其做法是,分配一个新的数组,然后将全部元素移到这个数组。就时间而言,这是一个相对代价高的任务,因为每当一个新的元素加入到容器的时候,vector并不会每次都重新分配大小。
4. vector分配空间策略:vector会分配一些额外的空间以适应可能的增长,因为存储空间比实际需要的存储空间更大。不同的库采用不同的策略权衡空间的使用和重新分配。但是无论如何,重新分配都应该是对数增长的间隔大小,以至于在末尾插入一个元素的时候是在常数时间的复杂度完成的。
5. 因此,vector占用了更多的存储空间,为了获得管理存储空间的能力,并且以一种有效的方式动态增长。
6. 与其它动态序列容器相比(deques, lists and forward_lists), vector在访问元素的时候更加高效,在末尾添加和删除元素相对高效。对于其它不在末尾的删除和插入操作,效率更低。比起lists和forward_lists统一的迭代器和引用更好。
学习方法:使用STL的三个境界:能用,明理,能扩展 ,那么下面学习vector,我们也是按照这个方法去学习

1.2 vector的使用

vector学习时一定要学会查看文档:vector的文档介绍,vector在实际中非常的重要,在实际中我们熟悉常见的接口就可以,下面列出了哪些接口是要重点掌握的

1.2.1 vector的定义

 

// constructing vectors
#include <iostream>
#include <vector>
int main ()
{
 // constructors used in the same order as described above:
 std::vector<int> first; // empty vector of ints
 std::vector<int> second (4,100); // four ints with value 100
 std::vector<int> third (second.begin(),second.end()); // iterating through second
 std::vector<int> fourth (third); // a copy of third
 // 下面涉及迭代器初始化的部分,我们学习完迭代器再来看这部分
 // the iterator constructor can also be used to construct from arrays:
 int myints[] = {16,2,77,29};
 std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );
 std::cout << "The contents of fifth are:";
 for (std::vector<int>::iterator it = fifth.begin(); it != fifth.end(); ++it)
 std::cout << ' ' << *it;
 std::cout << '\n';
 return 0; 
}

1.2.2 vector iterator 的使用

#include <iostream>
#include <vector>
using namespace std;
void PrintVector(const vector<int>& v) {
	// const对象使用const迭代器进行遍历打印
	vector<int>::const_iterator it = v.begin();
	while (it != v.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
}
int main()
{
	// 使用push_back插入4个数据
	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);
	v.push_back(4);
	// 使用迭代器进行遍历打印
	vector<int>::iterator it = v.begin();
	while (it != v.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
	// 使用迭代器进行修改
	it = v.begin();
	while (it != v.end())
	{
		*it *= 2;
		++it;
	}
	// 使用反向迭代器进行遍历再打印
	vector<int>::reverse_iterator rit = v.rbegin();
	while (rit != v.rend())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;
	PrintVector(v);
	return 0;
}

1.2.3 vector 空间增长问题 

(1)capacity的代码在vs和g++下分别运行会发现,vs下capacity是按1.5倍增长的,g++是按2倍增长的。这个问题经常会考察,不要固化的认为,顺序表增容都是2倍,具体增长多少是根据具体的需求定义的。vs是PJ版本STL,g++是SGI版本STL。
(2)reserve只负责开辟空间,如果确定知道需要用多少空间,reserve可以缓解vector增容的代价缺陷问题。
(3)resize在开空间的同时还会进行初始化,影响size。
// vector::capacity
#include <iostream>
#include <vector>
int main()
{
	size_t sz;
	std::vector<int> foo;
	sz = foo.capacity();
	std::cout << "making foo grow:\n";
	for (int i = 0; i < 100; ++i)
	{
		foo.push_back(i);
		if (sz != foo.capacity()) 
		{
			sz = foo.capacity();
			std::cout << "capacity changed: " << sz << '\n';
		}
	}
}
vs:运行结果:
making foo grow :
capacity changed : 1
capacity changed : 2
capacity changed : 3
capacity changed : 4
capacity changed : 6
capacity changed : 9
capacity changed : 13
capacity changed : 19
capacity changed : 28
capacity changed : 42
capacity changed : 63
capacity changed : 94
capacity changed : 141
g++运行结果:
making foo grow :
capacity changed : 1
capacity changed : 2
capacity changed : 4
capacity changed : 8
capacity changed : 16
capacity changed : 32
capacity changed : 64
capacity changed : 128
// vector::reserve
#include <iostream>
#include <vector>
int main()
{
	size_t sz;
	std::vector<int> foo;
	sz = foo.capacity();
	std::cout << "making foo grow:\n";
	for (int i = 0; i < 100; ++i) {
		foo.push_back(i);
		if (sz != foo.capacity()) {
			sz = foo.capacity();
			std::cout << "capacity changed: " << sz << '\n';
		}
	}
	std::vector<int> bar;
	sz = bar.capacity();
	bar.reserve(100); // this is the only difference with foo above
	std::cout << "making bar grow:\n";
	for (int i = 0; i < 100; ++i) {
		bar.push_back(i);
		if (sz != bar.capacity()) {
			sz = bar.capacity();
			std::cout << "capacity changed: " << sz << '\n';
		}
	}
	return 0;
}
// vector::resize
#include <iostream>
#include <vector>
int main()
{
	std::vector<int> myvector;
	// set some initial content:
	for (int i = 1; i < 10; i++)
		myvector.push_back(i);
	myvector.resize(5);
	myvector.resize(8, 100);
	myvector.resize(12);
	std::cout << "myvector contains:";
	for (int i = 0; i < myvector.size(); i++)
		std::cout << ' ' << myvector[i];
	std::cout << '\n';
	return 0;
}

 1.2.3 vector 增删查改

// push_back/pop_back
#include <iostream>
#include <vector>
using namespace std;
int main()
{
	int a[] = { 1, 2, 3, 4 };
	vector<int> v(a, a + sizeof(a) / sizeof(int));
	vector<int>::iterator it = v.begin();
	while (it != v.end()) 
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
	v.pop_back();
	v.pop_back();
	it = v.begin();
	while (it != v.end()) 
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
	return 0;
}

// find / insert / erase
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
	int a[] = { 1, 2, 3, 4 };
	vector<int> v(a, a + sizeof(a) / sizeof(int));
	// 使用find查找3所在位置的iterator
	vector<int>::iterator pos = find(v.begin(), v.end(), 3);

	// 在pos位置之前插入30
	v.insert(pos, 30);
	vector<int>::iterator it = v.begin();
	while (it != v.end()) 
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
	pos = find(v.begin(), v.end(), 3);
	// 删除pos位置的数据
	v.erase(pos);
	it = v.begin();
	while (it != v.end()) 
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
	return 0;
}

// operator[]+index 和 C++11中vector的新式for+auto的遍历
// 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;
}

 STL库中的全排列:

 

//STL库中的全排列
#include<iostream>
#include<algorithm>
#include<vector>
using  namespace std;

int main()
{
	vector<int> v = { 2,1,4,3 };
	//sort(v.begin(), v.end());				//默认为升序
	sort(v.begin(), v.end(),greater<int>());//默认为升序
	do
	{
		for (auto e : v)
		{
			cout << e << " ";
		}
		cout << endl;
	//} while (next_permutation(v.begin(), v.end()));  //升序
	} while (prev_permutation(v.begin(), v.end()));    //降序

	return 0;
}

 

1.2.4 vector 迭代器失效问题。(重点)

迭代器的主要作用就是让算法能够不用关心底层数据结构,其底层实际就是一个指针,或者是对指针进行了封装,比如:vector的迭代器就是原生态指针T*。因此迭代器失效,实际就是迭代器底层对应指针所指向的空间被销毁了,而使用一块已经被释放的空间,造成的后果是程序崩溃(即如果继续使用已经失效的迭代器,程序可能会崩溃)。
对于vector可能会导致其迭代器失效的操作有:
1. 会引起其底层空间改变的操作,都有可能是迭代器失效,比如:resize、reserve、insert、assign、push_back等。
#include <iostream>
using namespace std;
#include <vector>
int main()
{
	vector<int> v{ 1,2,3,4,5,6 };

	auto it = v.begin();

	// 将有效元素个数增加到100个,多出的位置使用8填充,操作期间底层会扩容
	// v.resize(100, 8);

	// reserve的作用就是改变扩容大小但不改变有效元素个数,操作期间可能会引起底层容量改变
	// v.reserve(100);

	// 插入元素期间,可能会引起扩容,而导致原空间被释放
	// v.insert(v.begin(), 0);
	 // v.push_back(8);

    // 给vector重新赋值,可能会引起底层容量改变
	v.assign(100, 8);

	/*
	出错原因:以上操作,都有可能会导致vector扩容,也就是说vector底层原理旧空间被释放掉,
   而在打印时,it还使用的是释放之间的旧空间,在对it迭代器操作时,实际操作的是一块已经被释放的
   空间,而引起代码运行时崩溃。
	解决方式:在以上操作完成之后,如果想要继续通过迭代器操作vector中的元素,只需给it重新
   赋值即可。
	*/
	while (it != v.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
	return 0;
}

2. 指定位置元素的删除操作--erase

#include <iostream>
using namespace std;
#include <vector>
int main()
{
	int a[] = { 1, 2, 3, 4 };
	vector<int> v(a, a + sizeof(a) / sizeof(int));
	// 使用find查找3所在位置的iterator
	vector<int>::iterator pos = find(v.begin(), v.end(), 3);
	// 删除pos位置的数据,导致pos迭代器失效。
	v.erase(pos);
	cout << *pos << endl; // 此处会导致非法访问
	return 0;
}
erase删除pos位置元素后,pos位置之后的元素会往前搬移,没有导致底层空间的改变,理论上讲迭代器不应该会失效,但是:如果pos刚好是最后一个元素,删完之后pos刚好是end的位置,而end位置是没有元素的,那么pos就失效了。因此删除vector中任意位置上元素时,vs就认为该位置迭代器失效了。
以下代码的功能是删除vector中所有的偶数,请问那个代码是正确的,为什么?
#include <iostream>
using namespace std;
#include <vector>
int main()
{
	vector<int> v{ 1, 2, 3, 4 };
	auto it = v.begin();
	while (it != v.end())
	{
		if (*it % 2 == 0)
			v.erase(it);
		++it;
	}

	return 0;
}
int main()
{
	vector<int> v{ 1, 2, 3, 4 };
	auto it = v.begin();
	while (it != v.end())
	{
		if (*it % 2 == 0)
			it = v.erase(it);
		else
			++it;
	}
	return 0;
}

迭代器失效解决办法:在使用前,对迭代器重新赋值即可

1.2.5 vector 在OJ中的使用

1. 只出现一次的数字:
class Solution
{
public:
	int singleNumber(vector<int>& nums)
	{
		int value = 0;
		for (auto e : v)
		{
			value ^= e;
		}
		return value;
	}
};
2. 杨辉三角OJ:
// 涉及resize / operator[]
class Solution 
{
public:
	// 核心思想:找出杨辉三角的规律,发现每一行头尾都是1,中间第[j]个数等于上一行[j-1]+
	[j]
	vector<vector<int>> generate(int numRows) {
		vector<vector<int>> vv;
		// 先开辟杨辉三角的空间
		vv.resize(numRows);
		for (size_t i = 1; i <= numRows; ++i)
		{
			vv[i - 1].resize(i, 0);
			// 每一行的第一个和最后一个都是1
			vv[i - 1][0] = 1;
			vv[i - 1][i - 1] = 1;
		}
		for (size_t i = 0; i < vv.size(); ++i)
		{
			for (size_t j = 0; j < vv[i].size(); ++j)
			{
				if (vv[i][j] == 0)
				{
					vv[i][j] = vv[i - 1][j - 1] + vv[i - 1][j];
				}
			}
		}
		return vv;
	}
};
总结:通过上面的练习我们发现vector常用的接口更多是插入和遍历。遍历更喜欢用数组operator[i]的形式访问,因为这样便捷。课下除了再自己实现一遍上面课堂讲解的OJ练习,请自行完成下面题目的OJ 练习。以此增强学习vector的使用

class Solution 
{
	string _numToStr[10] = { "","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz" };

public:
	void _letterCombine(string digits, size_t di, string combineStr, vector<string>& retV)
	{
		if (di == digits.size())
		{
			retV.push_back(combineStr);
			return;
		}
		//取到数字字符转换成数字,再存放到映射的字符串
		int num = digits[di] - '0';
		string str = _numToStr[num];
		for (auto ch : str)
		{
			_letterCombine(digits, di + 1, combineStr + ch, retV);
		}
	}
	vector<string> letterCombinations(string digits) 
	{
		vector<string> retV;
		if (digits.empty())
			return retV;

		size_t i = 0;
		string str;
		_letterCombine(digits, i, str, retV);
		return retV;
	}
};

 2.常用接口测试:

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

void TestVector1()
{
	vector<int> v1;
	v1.push_back(1);
	v1.push_back(2);
	v1.push_back(3);

	vector<double> v2;
	v2.push_back(1.1);
	v2.push_back(1.2);
	v2.push_back(1.3);
	
	vector<string> v3; //string支持单参数隐式类型转换
	v3.push_back("李白");
	v3.push_back("杜甫");
	v3.push_back("苏轼");
	v3.push_back("王维");
	
	vector<int> v4(10, 5);
	vector<string> v5(++v3.begin(), --v3.end());

	string s = "hello,world";
	vector<char> v6(s.begin(), s.end());
}
void TestVector2()
{
	vector<int> v1;
	v1.push_back(1);
	v1.push_back(2);
	v1.push_back(3);
	//遍历
	//方式1:下标+[]
	for (size_t i = 0; i < v1.size(); ++i)
	{
		cout << v1[i] << " ";
		v1[i] += 1;
	}
	cout << endl;
	//方式2:迭代器
	vector<int>::iterator it = v1.begin();
	while (it != v1.end())
	{
		*it -= 1;
		cout << *it << " ";
		++it;
	}
	cout << endl;
	//方式3:范围for
	for (auto e : v1)
	{
		cout << e << " ";
	}
}
void TestVector3()
{
	vector<char> v1;  
	cout << v1.max_size() << endl;  //2^32-1,打印却是2^31-1  有出入????
	vector<int> v2;					
	cout << v2.max_size() << endl; //vector<char>/4  2^30-1
	vector<double> v3;
	cout << v3.max_size() << endl; //2^29-1

}
//vector::capacity
void TestVector4()
{  
	//单次增容问题分析:
	//单次增容越多,插入N个值,增容次数越少,效率就越高,但可能浪费空间就越多
	//单次增少了,需要 多次增容,效率低下
	//vs环境:增容倍数为1.5倍
	//Linux g++环境:增容倍数为2倍

	size_t sz;
	std::vector<int> foo;
	sz = foo.capacity();
	std::cout << "making foo grow:\n";
	for (int i = 0; i < 100; ++i) 
	{
		foo.push_back(i);
		if (sz != foo.capacity())
		{
			sz = foo.capacity();
			std::cout << "capacity changed: " << sz << '\n';
		}
	}
}
//vector::reserve
void TestVector5()
{
	size_t sz;
	std::vector<int> foo;
	sz = foo.capacity();
	std::cout << "making foo grow:\n";
	for (int i = 0; i < 100; ++i)
	{
		foo.push_back(i);
		if (sz != foo.capacity())
		{
			sz = foo.capacity();
			std::cout << "capacity changed: " << sz << '\n';
		}
	}
	std::vector<int> bar;
	sz = bar.capacity();
	bar.reserve(100); // this is the only difference with foo above
	std::cout << "making bar grow:\n";
	for (int i = 0; i < 100; ++i)
	{
		bar.push_back(i);
		if (sz != bar.capacity()) 
		{
			sz = bar.capacity();
			std::cout << "capacity changed: " << sz << '\n';
		}
	}

}
//vector::resize
void TestVector6()
{
	std::vector<int> myvector;
	// set some initial content:
	for (int i = 1; i < 10; i++)
		myvector.push_back(i);
	myvector.resize(5);
	myvector.resize(8, 100);
	myvector.resize(12);
	std::cout << "myvector contains:";
	for (int i = 0; i < myvector.size(); i++)
		std::cout << ' ' << myvector[i];
	std::cout << '\n';
}
void TestVector7()
{
	//string、vector等都有一个特点:删除数据,一般不会主动缩容
	std::vector<int> v;
	v.resize(10);
	cout << v.size() << endl;
	cout << v.capacity() << endl;
	//慎用:有代价,且操作系统会管理内存分配,人为很少干涉内存部分管理
	v.shrink_to_fit();
	cout << v.size() << endl;
	cout << v.capacity() << endl;
}
void TestVector8()
{
	vector<int> v1;
	v1.push_back(1);
	v1.push_back(2);
	v1.push_back(3);

	v1.insert(v1.begin(), -1); //vector附用迭代器
	v1.insert(v1.begin(), -2); //vector附用迭代器
	v1.insert(v1.begin(), -3); //vector附用迭代器

	for (auto e : v1)          //范围for遍历
	{
		cout << e << " ";
	}
	cout << endl;
	//vector 不再支持下标定位插入
	//只能自己计算位置
	v1.insert(v1.begin() + 4, 90);
	for (auto e : v1)          //范围for遍历
	{
		cout << e << " ";
	}
}
void TestVector9()
{
	vector<int> v1;
	v1.push_back(1);
	v1.push_back(2);
	v1.push_back(3);
	v1.push_back(4);
	v1.push_back(5);

	v1.erase(v1.begin());
	for (auto e : v1)          //范围for遍历
	{
		cout << e << " ";
	}
}
void TestVector10()
{
	//vector、list不支持find,但可以附用algorithm的find
	vector<int> v1;
	v1.push_back(1);
	v1.push_back(2);
	v1.push_back(3);
	v1.push_back(4);
	//vector<int>::iterator pos=find(v1.begin(), v1.end(), 3);
	auto pos = find(v1.begin(), v1.end(), 3);  //左闭右开
	if (pos != v1.end())
	{
		cout << "找到了" << endl;
		//v1.erase(pos);
	}
	else
	{
		cout << "没有找到" << endl;
	}
	for (auto e : v1)
	{
		cout << e << " ";
	}
}
void TestVector11()
{
	vector<int> v1;
	v1.push_back(1);
	v1.push_back(6);
	v1.push_back(8);
	v1.push_back(7);
	v1.push_back(9);
	v1.push_back(2);
	v1.push_back(1);
	v1.push_back(4);
	for (auto e : v1)
	{
		cout << e << " ";
	}
	cout << endl;
	//sort(v1.begin(), v1.end());              //默认是升序
	//sort(v1.begin(), v1.end(),greater<int>()); //降序,加一个仿函数
	                                           greater<int>(); //构造一个匿名对象
	greater<int> g;
	sort(v1.begin(), v1.end(), g);
	for (auto e : v1)
	{
		cout << e << " ";
	}
}

int main()
{
	//TestVector1();
	//TestVector2();
	//TestVector3();
	//TestVector4();
	//TestVector5();
	//TestVector6();
	//TestVector7();
	//TestVector8();
	//TestVector9();
	//TestVector10();
	TestVector11();

	return 0;
}

后记:
●由于作者水平有限,文章难免存在谬误之处,敬请读者斧正,俚语成篇,恳望指教!
                                                                    ——By 作者:新晓·故知

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值