【C++】vector容器

版权声明:本文为博主原创文章,未经博主允许不得转载,博客地址:http://blog.csdn.net/mars_xiaolei。 https://blog.csdn.net/mars_xiaolei/article/details/82882584

参考书籍:《大道至简》

目录

vector元素访问方法

定义vector对象

vector常用函数

遍历vector容器

vector元素的查找和搜索

vector交换对象


vector是最简单的序列式容器,支持随机访问元素。vector作为动态数组使用是非常方便的,基本上可以实现数据结构队列数组堆栈的所有功能。

vector元素访问方法

可以直接访问vector的操作方法主要包括at()[]front()back()。第一个元素下标为0,最后一个元素下标为size()-1,即第n个元素的下标为n-1。

c.at(index);
c[index];
c.front();
c.back();

 1、c.at(index)函数的返回值是引用类型。该函数既可以取出元素值,也可以对元素进行赋值。

 2、c[index]的返回值是引用类型。该函数既可以取出元素,也可以对元素赋值,但必须确定下标是有效的。

 3、c.front()函数用于返回第一个元素。

 4、c.back()函数用于返回最后一个元素。

定义vector对象

vector<类型名> 对象名;

vector<typename T> c;

vector常用函数

1、push_back():将元素添加到容器中

void push_back(value_type_Ch);

2、reserve():预先设置容器的大小

void reserve(size_type _Count)

3、size():容器中现有的元素数

size_type size() const

4、capacity():容器实际能够容纳的元素数

size_type capacity() const

5、max_size():容器容纳的最大元素数

size_type max_size() const

6、resize():修改容器的大小

void resize(size_type _Newsize)
void resize(size_type _Newsize, _Ty _Val)

7、pop_back():删除最后一个元素

void pop_back()

8、insert():插入元素

iterator insert(const_iterator _Where, _Valty&& _Val)

9、erase():删除元素

iterator erase(const_iterator _Where)
iterator erase(const_iterator _First_arg,const_iterator _Last_arg)

10、clear():清空所有元素

void clear()
{	
    // erase all
	erase(begin(), end());
}

11、empty():判断容器是否为空,如果为空,则为真;否则为非真

bool empty() const
{	
    // test if sequence is empty
	return (this->_Myfirst == this->_Mylast);
}

这里要注意的是resize()这个函数,它会影响到size()capacity()的值,具体情况自己设置值进行调试。

void resize (size_type n);
void resize (size_type n, value_type val);

(1)当n小于当前size()值时候,vector首先会减少size()值 保存前n个元素,然后将超出n的元素删除(remove and destroy);

(2)当n大于当前size()值时候,vector会插入相应数量的元素 使得size()值达到n,并对这些元素进行初始化,如果调用上面的第二个resize函数,指定val,vector会用val来初始化这些新插入的元素;

(3)当n大于capacity()值的时候,会自动分配重新分配内存存储空间。

下面是常用函数使用示例:

#include "iostream"
#include "string"
#include "vector"

using namespace std;

int main()
{
	cout<<"------------1--------------"<<endl;
	vector<string> hello;//<定义vector对象,数据类型为string
	hello.reserve(4);//<预先设置容器的大小
	hello.push_back("1、北京");
	hello.push_back("2、天津");
	hello.push_back("3、上海");
	hello.push_back("4、成都");
	vector<string>::iterator it;
	for (it=hello.begin();it!=hello.end();it++)
	{
		cout<<*it<<endl;
	}
	int m=hello.size();//<容器中现有的元素数
	int n=hello.capacity();//<容器实际能够容纳的元素数
	int p=hello.max_size();//<容器容纳的最大元素数
	cout<<"size is:"<<m<<endl;
	cout<<"capacity is:"<<n<<endl;
	cout<<"max_size is:"<<p<<endl;
	cout<<"------------2--------------"<<endl;
	hello.resize(10);//<修改容器的大小
	int m1=hello.size();//<容器中现有的元素数
	int n1=hello.capacity();//<容器实际能够容纳的元素数
	cout<<"size is:"<<m1<<endl;
	cout<<"capacity is:"<<n1<<endl;
	for (it=hello.begin();it!=hello.end();it++)
	{
		if (*it=="")
		{
			cout<<"******"<<endl;
		}
		else
		{
			cout<<*it<<endl;
		}
	}
	if (hello.empty())
	{
		cout<<"vector is empty!"<<endl;
	}
	else
	{
		cout<<"vector is not empty!"<<endl;
	}
	cout<<"------------3--------------"<<endl;
	hello.resize(16);
	hello.pop_back();//<删除最后一个元素
	int m2=hello.size();//<容器中现有的元素数
	int n2=hello.capacity();//<容器实际能够容纳的元素数
	cout<<"size is:"<<m2<<endl;
	cout<<"capacity is:"<<n2<<endl;
	cout<<"------------4--------------"<<endl;
	hello.insert(hello.begin(),"0、重庆");//<在起始位置插入0、重庆
	hello.insert(hello.begin()+5,"5、深圳");//<在第6个位置插入5、深圳
	hello.insert(hello.end(),"15、南昌");//<在最后位置插入15、南昌
	for (it=hello.begin();it!=hello.end();it++)
	{
		if (*it=="")
		{
			cout<<"******"<<endl;
		}
		else
		{
			cout<<*it<<endl;
		}
	}
	cout<<"------------5--------------"<<endl;
	hello.erase(hello.begin());//<删除起始位置元素
	hello.erase(hello.begin()+4,hello.end());//<删除第5到结尾所有元素
	for (it=hello.begin();it!=hello.end();it++)
	{
		if (*it=="")
		{
			cout<<"******"<<endl;
		}
		else
		{
			cout<<*it<<endl;
		}
	}
	cout<<"------------6--------------"<<endl;
	hello.clear();//<清空所有元素
	int m3=hello.size();//<容器中现有的元素数
	int n3=hello.capacity();//<容器实际能够容纳的元素数
	cout<<"size is:"<<m3<<endl;
	cout<<"capacity is:"<<n3<<endl;
	//cin.get();
	system("pause");
	return 0;
}

输出结果:

------------1--------------
1、北京
2、天津
3、上海
4、成都
size is:4
capacity is:4
max_size is:134217727
------------2--------------
size is:10
capacity is:10
1、北京
2、天津
3、上海
4、成都
******
******
******
******
******
******
vector is not empty!
------------3--------------
size is:15
capacity is:16
------------4--------------
0、重庆
1、北京
2、天津
3、上海
4、成都
5、深圳
******
******
******
******
******
******
******
******
******
******
******
15、南昌
------------5--------------
1、北京
2、天津
3、上海
4、成都
------------6--------------
size is:0
capacity is:24
请按任意键继续. . .

遍历vector容器

要遍历vector中的元素,需要使用循环语句for或者while。可以使用迭代器遍历,也可以通过使用at()函数循环语句实现,下面是使用这几种方法遍历vector的示例:

#include "iostream"
#include "vector"

using namespace std;

struct Student
{
	int id;
	double db;
};

void InitParam(int num,vector<Student> &t);
void Iter_for(vector<Student> &t);
void at_for(vector<Student> &t);

int main()
{
	Student st;
	vector<Student> student;
	InitParam(5,student);
	cout<<"<----迭代器遍历---->"<<endl;
	Iter_for(student);
	cout<<"<----at遍历---->"<<endl;
	at_for(student);
	cout<<"<----while遍历---->"<<endl;
	while(!student.empty())
	{
		//st=student.back();//<return最后一个元素
		cout<<"id:"<<student.back().id<<", db:"<<student.back().db<<endl;
		student.pop_back();
	}
	system("pause");
	return 0;
}
//<初始化
//<num:输入参数,元素的个数
//<t:输出参数
void InitParam(int num,vector<Student> &t)
{
	int m=num;
	Student temp;
	for (int i=0;i<m;i++)
	{
		temp.id=i+1;
		temp.db=(i+1)*10;
		t.push_back(temp);
	}
}
//<迭代器遍历vector
void Iter_for(vector<Student> &t)
{
	Student temp;
	vector<Student> ::iterator it;
	for (it=t.begin();it!=t.end();it++)
	{
		temp=*it;
		cout<<"id:"<<temp.id<<", db:"<<temp.db<<endl;
	}
}
//<at遍历vector
void at_for(vector<Student> &t)
{
	Student temp;
	int m=t.size();
	for (int i=0;i<m;i++)
	{
		temp=t.at(i);
		cout<<"id:"<<temp.id<<", db:"<<temp.db<<endl;
	}
}

输出结果: 

<----迭代器遍历---->
id:1, db:10
id:2, db:20
id:3, db:30
id:4, db:40
id:5, db:50
<----at遍历---->
id:1, db:10
id:2, db:20
id:3, db:30
id:4, db:40
id:5, db:50
<----while遍历---->
id:5, db:50
id:4, db:40
id:3, db:30
id:2, db:20
id:1, db:10
请按任意键继续. . .

vector元素的查找和搜索

可以使用STL的通用算法find()函数来查找和搜索vector容器的元素,如果是有条件搜索相关元素,则可以使用find_if()算法函数,这两个函数均使用了迭代器,两个迭代器参数决定了查找和搜索的范围,并且这两个函数的返回值均为迭代器类型。

1、for_each()函数,将指定范围内的元素进行处理(函数),并返回对象

template<class _InIt, class _Fn1> inline
    _Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func);

2、find()函数,在指定值的范围内定位元素的第一次出现的位置

template<class InputIterator, class Type>
   InputIterator find(
      InputIterator _First, 
      InputIterator _Last, 
      const Type& _Val
   );

3、find_if()函数,在指定范围内有条件的搜索相关元素

template<class InputIterator, class Predicate>
   InputIterator find_if(
      InputIterator _First, 
      InputIterator _Last, 
      Predicate _Pred
   );

下面是vector元素的查找和搜索的示例代码:

#include "iostream"
#include "vector"
#include "algorithm"
#include "functional"

using namespace std;

void print(const int& temp);

int main()
{
	const int SIZE =8;
	int Array[SIZE]={1,2,3,4,5,6,7,8};
	vector<int> hello;
	vector<int>::iterator location_index;
	//int* location_index=NULL;
	for(int i=0;i<8;i++)
	{
		hello.push_back(Array[i]);
	}
	for_each(hello.begin(),hello.end(),print);//<输出容器中的所有元素
	location_index=find(hello.begin(),hello.end(),2);
	cout<<"数字2的下标是:"<<(location_index-hello.begin())<<endl;
	//<bind2nd:将2元算子转换为1元算子,greater:较大的,less:较小的
	location_index=find_if(hello.begin(),hello.end(),bind2nd(greater<int> (),5));
	cout<<"第一个大于5的数字的下标是:"<<(location_index-hello.begin())<<endl;
	system("pause");
	return 0;
}
//<打印
void print(const int& temp)
{
	cout<<temp<<endl;
}

输出结果:

1
2
3
4
5
6
7
8
数字2的下标是:1
第一个大于5的数字的下标是:5
请按任意键继续. . .

vector交换对象

要实现两个vector容器之间的元素互换,可以使用vector自带的swap()函数。如果两个参与交换的vector类型相同,则对象交换会瞬间完成;但是如果两个参与交换的vector对象中元素类型不相同,那么需要进行一些复杂的转化操作,才能进行交换。下面是交换对象的示例:

#include "iostream"
#include "vector"
#include "algorithm"

using namespace std;
void print(int &t);

int main()
{
	vector<int> a,b;
	for(int i=0;i<10;i++)
	{
		a.push_back(i);
		b.push_back(i*3);
	}
	cout<<"-------a------"<<endl;
	for_each(a.begin(),a.end(),print);
	cout<<endl;
	cout<<"-------b------"<<endl;
	for_each(b.begin(),b.end(),print);
	cout<<endl;
	a.swap(b);
	cout<<"-------swap-a------"<<endl;
	for_each(a.begin(),a.end(),print);
	cout<<endl;
	cout<<"-------swap-b------"<<endl;
	for_each(b.begin(),b.end(),print);
	cout<<endl;
	system("pause");
	return 0;
}
void print(int &t)
{
	cout<<t<<", ";
}

输出结果:

-------a------
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
-------b------
0, 3, 6, 9, 12, 15, 18, 21, 24, 27,
-------swap-a------
0, 3, 6, 9, 12, 15, 18, 21, 24, 27,
-------swap-b------
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
请按任意键继续. . .

猜你喜欢

转载自blog.csdn.net/mars_xiaolei/article/details/82882584