Vector使用总结
前言
模板类vector是一种动态数组,此篇用于总结它的常用方法。
使用vector
/* 需要导入头文件 */
#include <vector>
/* 通过命名空间 */
std::vector<Type> ...
/* 或者 using编译指令 */
using namespace std;
vector<Type> ...
/* 又或者 using声明 */
using std::vector;
vector<Type> ...
除了int,string,float等C++基本数据类型外,vector也支持存放我们自己设计的数据类型,但此时需要有对应的构造函数才能保证vector正常使用(尤其是拷贝构造函数)。简单示例如下:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Student {
private:
string name;
int age;
long id;
public:
Student(string name, int age, long id):
name(name), age(age), id(id)
{
}
Student(const Student& std) {
/* 拷贝构造函数 */
name = std.name;
age = std.age;
id = std.id;
}
friend ostream& operator<< (ostream& os, const Student& std);
};
ostream& operator<< (ostream& os, const Student& std)
{
return os << "{ " << std.name << " "
<< std.age << " " << std.id << " }";
}
int main()
{
vector<Student> stdV = {
{
"zty", 22, 20140010}, {
"you", 23, 20140011}};
vector<Student> stdV2(stdV);
cout << stdV2[0] << endl;
cout << stdV2[1] << endl;
return 0;
}
// 输出:
{
zty 22 20140010 }
{
you 23 20140011 }
容器构造
以下,利用构造函数构造容器。
1. 直接声明一个容器,此时容器为空,不能试图访问容器内部,否则段错误(Segmentation fault)。
vector<int> intV