本文为博主原创文章,未经博主允许不得转载。
https://blog.csdn.net/lxy_2011/article/details/52703216
一、今日课题
vector
二、实战演练
vector<type> variable_name (number_of_elements)
1)有何用?
Vectors 包含着一系列连续存储的元素,其行为和数组类似。访问Vector中的任意元素或从末尾添加元素都可以在常量级时间复杂度内完成,而查找特定值的元素所处的位置或是在Vector中插入元素则是线性时间复杂度。
2)怎么用?
- 头文件#include
- 创建vector对象,vector vec
- 代码示例
#include <iostream>
#include <vector>
#include<algorithm>
using namespace std;
typedef struct rect
{
int id;
int length;
int width;
//对于向量元素是结构体的,可在结构体内部定义比较函数,下面按照id,length,width升序排序
bool operator<(const rect &a) const
{
if (id != a.id)
return id < a.id;
else
{
if (length != a.length)
return length < a.length;
else
return width < a.length;
}
}
}Rect;
int main()
{
vector<Rect> vec;
Rect rect;
rect.id = 1;
rect.length = 2;
rect.width = 3;
vec.push_back(rect);
vector<Rect>::iterator it = vec.begin();
cout << (*it).id << ' ' << (*it).width << ' ' << (*it).length << endl;
system("pause"); return 0;
}
3)Access & Operations