【cpp--->vector】

文章详细介绍了C++标准库中的vector容器,包括构造、容量控制、访问、修改、比较等主要接口的使用方法,并提供了杨辉三角和电话号码字母组合的实战示例。此外,还讨论了vector类的模拟实现及其难点,如数据移动、插入删除操作的处理。
摘要由CSDN通过智能技术生成

一、vector主要接口介绍

1.构造

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

int main()
{
	//默认构造一个容器为空的对象,没有元素
	vector<int> v1;

	//用n个元素构造一个对象,val默认为T()
	vector<int> v2(3);
	vector<int> v3(3, 10);

	//用任意类型的迭代器区间构造一个对象
	string s("hello world");
	vector<char> v4(s.begin(), s.end() - 1);

	//拷贝构造
	vector<char> v5(v4);

	return 0;
}

在这里插入图片描述

2.容量控制

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

int main()
{
	vector<int> v1(10, 1);
	cout << "v1.size(): " << v1.size() << " " << "v1.capacity(): " << v1.capacity() << endl;

	//开空间加初始化,可以增加数据可以删减数据
	v1.resize(11, 2);
	cout << "v1.size(): " << v1.size() <<" " << "v1.capacity(): " << v1.capacity() << endl;
	for (auto e : v1)
	{
		cout << e << " ";
	}
	cout << endl;
	//删减数据
	v1.resize(10);
	cout << "v1.size(): " << v1.size() << " " << "v1.capacity(): " << v1.capacity() << endl;
	for (auto e : v1)
	{
		cout << e << " ";
	}
	cout << endl;
	//扩容,小于当前容量不处理
	v1.reserve(11);
	cout << "v1.size(): " << v1.size() << " " <<"v1.capacity(): " << v1.capacity() << endl;
	v1.reserve(100);
	cout << "v1.size(): " << v1.size() << " " << "v1.capacity(): " << v1.capacity() << endl;
	//缩容,缩容至等于size的大小
	v1.shrink_to_fit();
	cout << "v1.size(): " << v1.size() << " " << "v1.capacity(): " << v1.capacity() << endl;
	
	return 0;
}

在这里插入图片描述

3.访问

#include<iostream>
#include<vector>
using namespace std;
void  func(const vector<int>& v)
{
	cout << typeid(v[0]).name() << endl;
}
int main()
{
	int arr[] = { 3,4,5,6,8,7,6,8,7,11,13,15 };
	vector<int> v1(arr,arr+sizeof(arr)/sizeof(arr[0]));
	//访问队头和队尾数据
	cout << " v1.back(): " << v1.back() << endl;
	cout <<" v1.front(): " << v1.front()<< endl;
	//[]重载,返回val的引用,有普通val,也有const val
	cout << "++ : ";
	for (int i = 0; i < v1.size(); i++)
	{
		cout << ++v1[i] << " ";
	}
	cout << endl;
	//const val
	func(v1);
	return 0;
}

在这里插入图片描述

4.修改

1.尾插和尾删

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

int main()
{
	vector<int> v1;
	//尾插和尾删
	v1.push_back(1);
	v1.push_back(2);
	v1.push_back(3);
	v1.push_back(4);
	for (auto e : v1)
	{
		cout << e;
	}
	cout << endl;
	//尾删
	v1.pop_back();
	for (auto e : v1)
	{
		cout << e;
	}
	cout << endl;
	return 0;
}

在这里插入图片描述

2.任意位置插入和删除

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

int main()
{
	string s("hello world");
	vector<char> v1(s.begin(),s.end());
	
	//任意迭代器位置插入一个val,返回插入位置的迭代器位置
	v1.insert(v1.begin() + 4, ' ');

	//任意迭代器位置插入n个val,返回插入位置的迭代器位置
	v1.insert(v1.begin() + 6, 3, 'x');

	//任意迭代器位置插入任意类型的迭代器区间,返回插入位置的迭代器位置
	v1.insert(v1.begin() + 9, s.begin(), s.end());
	
	//删除任意位置的一个val,返回删除位置的下一个位置的迭代器位置
	v1.erase(v1.begin() + 4);

	//删除任意迭代器区间,返回删除位置的下一个位置的迭代器位置
	v1.erase(v1.begin() + 5, v1.end() - 6);
	return 0;
}

在这里插入图片描述

5.比较

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

int main()
{
	vector<string> v1 = {"hello"};
	vector<string> v2{"world"};
	cout << (v1 == v2) << endl;
	cout << (v1 < v2) << endl;
	cout << (v1 <= v2) << endl;
	cout << (v1 > v2) << endl;
	cout << (v1 >= v2) << endl;
	return 0;
}

在这里插入图片描述

二、vector接口实战应用

1.杨辉三角

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> vv(numRows);
        //给vector中的vector开空间并初始化
        for(int i=0;i<numRows;i++)
        {
            vv[i].resize(i+1,1);
        }
        //计算杨慧三角
        for(int i=2;i<numRows;i++)
        {
            for(int j=1;j<vv[i].size()-1;j++)
            {
                vv[i][j]=vv[i-1][j-1]+vv[i-1][j];
            }
        }
        return vv;
    }
};

2.电话号码的字母组合

vector<string> vstr{{},{},{"abc"},{"def"},{"ghi"},{"jkl"},{"mno"},{"pqrs"},{"tuv"},{"wxyz"}};
class Solution {
public:
    void _letterCombinations(const string& digits,int id
    ,string combinations,vector<string>& result)
    {
        //digits中的数字读完则记录组合并返回
        if(id==digits.size())
        {
            result.push_back(combinations);
            return;
        }
        //将digits中的数字字符转整型
        int vstrId=digits[id]-'0';
        //遍历记录一个数字对应按键中的所有字母
        for(auto e: vstr[vstrId])
        {
            //全排列digits中所有数字的对应按键中的字母,排列一组临时记录在combinations
            //记录到最后一个按键的字母就传递给result,然后重头开始记录。
            _letterCombinations(digits,id+1,combinations+e,result);
        }
    }
    vector<string> letterCombinations(string digits) {
        //没有按按键的时候返回空数组
        if(digits.size()==0)
        {
            return vector<string>();
        }
        //记录结果
        vector<string> result;
        //临时记录组合
        string combinations;
        _letterCombinations(digits,0,combinations,result);
        return result;
    }
};

三、vector类模拟实现

1.实现难点

在构造实现过程中使用push_back或者reserve这些接口需要初始化成员变量,赋值构造和拷贝构造的数据拷贝应避免深层次的浅拷贝,不能用内存拷贝这些接口直接拷贝,因为有可能start存储的是自定义类型。

任意位置的插入和删除都需要用到pos,pos在insert扩容后是失效的,因为扩容后start地址发生变化,之前的pos是根据没改变时候的start确定的地址。所以pos需要在扩容前记录相对位置,扩容后根据相对位置找到当前位置。删除后pos也是失效的,因为pos如果是finish的前一个数据,再访问pos就越界访问了。

在数据移动的时候,需要特别注意控制end的访问区间,end不能访问没有开辟的空间,也就是不能方位>=end_of_storage的空间。

2.代码实现

#pragma once
#include<iostream>
#include<string>
#include<assert.h>
using namespace std;
namespace kk
{
	template <class T>
	class vector
	{
	public:
		typedef T* iterator;
		typedef const T* const_iterator;
	public:
		//begin
		iterator begin()
		{
			return _start;
		}
		//end
		iterator end()
		{
			return _finish;
		}
		// const_begin
		const_iterator begin()const
		{
			return _start;
		}
		// const_end
		const_iterator end()const
		{
			return _finish;
		}
		//构造
		vector()
			:_start(nullptr)
			, _finish(nullptr)
			, _end_of_storage(nullptr)
		{}
		//拷贝构造
		vector(const vector<T>& v)
		{
			_start = new T[v.capacity()];
			if (v._start)
			{
				//vector内部可能存储的是自定义类型比如string,直接使用
				//内存拷贝会曹成深层次的浅拷贝问题,对象内部的str地址相同
				//所以需要使用自定义类型的复制构造。
				for (int i = 0; i < v.size(); i++)
				{
					*(_start+i) = *(v._start+i);
				}
			}
			_finish = _start+v.size();
			_end_of_storage = _start+v.capacity();
		}
		vector(const T& val)
		{
			reserve(4);
			*_start = val;
			_finish = _start + 1;
		}
		vector(size_t n,const T& val = T())
		{
			reserve(n);
			for (int i = 0; i < n; i++)
			{
				push_back(val);
			}
		}
		//赋值构造
		vector<T>& operator=(vector<T> v)
		{
			std::swap(_start, v._start);
			std::swap(_finish, v._finish);
			std::swap(_end_of_storage, v._end_of_storage);
			return *this;
		}
		// 扩容
		void resize(size_t n, const T& val = T())
		{
			//小于数据长度
			if (n < size())
			{
				//直接调整finish的位置
				_finish = _start + n;
			}
			//大于数据长度
			else
			{
				//扩容
				if (n > capacity())
				{
					reserve(n);
				}
				//初始化多余的空间,更新_finish
				while (_finish != _start + n)
				{
					*_finish = val;
					++_finish;
				}
			}
		}
		// 扩容加初始化
		void reserve(size_t n)
		{
			if (n > capacity())
			{
				//开新空间
				iterator tmp = new T[n];
				//使用赋值拷贝将原来的数据拷贝至新开空间
				for (int i = 0; i < size(); i++)
				{
					*(tmp + i) = *(_start + i);
				}
				//_start一旦改变就求不出数据长度了,所以提前记录
				size_t len = size();
				//释放旧空间
				delete[] _start;
				//更新成员位置
				_start = tmp;
				_finish = _start + len;
				_end_of_storage = _start + n;
			}
		}
		//尾插
		void push_back(const T& val )
		{
			insert(end(), val);
		}
		//尾插
		void pop_back()
		{
			erase(end());
		}
		//任意位置插入
		iterator insert(iterator pos, const T& val)
		{
			//断言pos位置
			assert(pos >= begin() && pos <= end());
			//扩容
			if (size() + 1 > capacity())
			{
				size_t len = pos - _start;
				reserve(capacity() == 0 ? 4 : capacity() * 2);
				pos = _start + len;
			}
			//移动数据
			iterator end = _finish;
			while (end != pos)
			{
				*end = *(end-1);
				end--;
			}
			//插入数据更新finish
			*pos = val;
			_finish++;
			return pos;
		}
		iterator insert(iterator pos,size_t n,const T& val)
		{
			//断言pos位置
			assert(pos >= begin() && pos <= end());
			//扩容
			if (size() + n > capacity())
			{
				size_t len = pos - _start;
				reserve(size()+n);
				pos = _start + len;
			}
			//移动数据.因为end_of_storage==finish+n所以不能访问finish+n
			iterator end = _finish+n-1;
			while (end != pos+n-1)
			{
				*end = *(end - n);
				end--;
			}
			//插入数据更新finish
			iterator retPos = pos;
			iterator endPos = pos + n;
			while (pos != endPos)
			{
				*(pos++) = val;
			}
			_finish += n;
			return retPos;
		}
		//任意位置删除
		iterator erase(iterator pos)
		{
			//断言pos位置
			assert(pos >= begin() && pos < end());
			//移动数据,end不能等于pos,这样end+1可能会越界
			iterator end = pos+1;
			while (end != _finish)
			{
				*(end - 1) = *end;
				end++;
			}
			//更新finish
			_finish--;
			return pos;
		}
		iterator erase(iterator first,iterator last)
		{
			assert(first >= begin() && first < end());
			assert(last >= begin() && last >= first && last <= end());
			//记录剩余last至finish数据长度
			size_t overLenght = _finish - last;
			//记录删除数据长度
			size_t eraseLenght = last - first;
			//覆盖被删除的数据空间
			for (int i = 0; i < overLenght; i++)
			{
				*(first++) = *(last++);
			}
			//更新数据长度
			_finish -= eraseLenght;
			return first;

		}
		T& operator[](size_t pos)
		{
			return _start[pos];
		}
		const T& operator[](size_t pos)const
		{
			return _start[pos];
		}
		//获取容量
		size_t size()const 
		{
			return _finish - _start;
		}
		//获取数据长度
		size_t capacity()const
		{
			return _end_of_storage - _start;
		}
	private:
		iterator _start=nullptr;
		iterator _finish=nullptr;
		iterator _end_of_storage=nullptr;
	};
	void test_vector1()
	{
		string s("hello world");
		kk::vector<std::string> vstr1(s);
		kk::vector<std::string> vstr2(vstr1);
		kk::vector<string> vstr3;
		vstr3 = vstr2;
	}
	void test_vector2()
	{
		string s("hello world");
		kk::vector<std::string> vs(s);

		vs.insert(vs.begin(), 2, " yyy ");
		vs.insert(vs.end()," xxx");
		vs.insert(vs.end() - 1, " zzz");
		for (auto e : vs)
		{
			cout << e;
		}
		cout << endl;
	}
	void test_vector3()
	{

		string s("hello world");
		kk::vector<std::string> vs(s);

		kk::vector<string>::iterator pos=vs.insert(vs.begin(), 2, " xxx ");
		for (auto e : vs)
		{
			cout << e;
		}
		cout << endl;

		vs.erase(pos);
		for (auto e : vs)
		{
			cout << e;
		}
		cout << endl;

		vs.insert(vs.begin(), " xxx ");
		for (auto e : vs)
		{
			cout << e;
		}
		cout << endl;
		vs.erase(vs.begin()+1,vs.end()-1);
		for (auto e : vs)
		{
			cout << e;
		}
		cout << endl;
	}
	void test_vector4()
	{

		string s("hello world");
		kk::vector<std::string> vs(s);
		cout << "vs.size(): " << vs.size() << " " << " vs.capacity: " << vs.capacity() << endl;
		vs.push_back(" xxx");
		vs.push_back(" yyy");
		vs.push_back(" zzz");
		vs.push_back(" iii");
		for (auto e : vs)
		{
			cout << e;
		}
		cout << endl;
		cout <<"vs.size(): " << vs.size() <<" " << " vs.capacity: " << vs.capacity() << endl;
	}
	void test_vector5()
	{

		string s("hello world");
		kk::vector<std::string> vs(s);
		vs.push_back(" xxx");
		vs.push_back(" yyy");
		vs.push_back(" zzz");
		vs.push_back(" iii");
		for (int i = 0; i < vs.size(); i++)
		{
			cout << vs[i];
		}
		cout << endl;
	}
}

3.容易出错的地方

在这里插入图片描述


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值