1 行为方式
1、Vector每添加一个对象,就会进行一轮调用拷贝构造函数创建新对象;
2、若添加对象时容量不足
(1)先通过拷贝构造出来创建新对象;
(2)进行扩容迁移原先的对象;
(3)添加(1)步骤中创建的新对象;
3、若vector初始化时未指定capacity容量,则每添加一个对象,容量与元素个数从0开始依次增加1;
2 vector添加对象方式1
2.1 示例
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class A
{
private:
int value;
public:
A() { value = 0;cout << "A() this= " << this << ",value="<<value<<endl; }
A(const A& a) {
cout << "A(A&) this= " << this << endl;
this->value = a.value;
}
void setValue(int value) { this->value = value; }
int getValue() { return this->value; }
};
int main()
{
vector<A> v;
cout << endl << "start create object of A:" << endl;
A a1, a2, a3;
a1.setValue(1);
a2.setValue(2);
a3.setValue(3);
cout << endl << "start push:" << endl;
cout << endl << "start push a1:" << endl;
v.push_back(a1);
cout << endl << "start push a2:" << endl;
v.push_back(a2);
cout << endl << "start push a3:" << endl;
v.push_back(a3);
cout << endl<<"start setValue:" << endl;
a1.setValue(4);
a2.setValue(5);
a3.setValue(6);
cout << endl << "start for:" << endl;
for (auto & a : v)
{
cout << &a << ",value="<<a.getValue()<<endl;
}
}
2.2 运行
start create object of A:
A() this= 00AFFDE8,value=0
A() this= 00AFFDDC,value=0
A() this= 00AFFDD0,value=0
start push:
start push a1:
A(A&) this= 00C160E8
start push a2:
A(A&) this= 00C1B46C
A(A&) this= 00C1B468
start push a3:
A(A&) this= 00C1B4A8
A(A&) this= 00C1B4A0
A(A&) this= 00C1B4A4
start setValue:
start for:
00C1B4A0,value=1
00C1B4A4,value=2
00C1B4A8,value=3
备注:
Vector初始化后
添加a1后
添加a2后
添加a3后
3 vector添加对象方式2(指定容量)
3.1 示例
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class A
{
private:
int value;
public:
A() { value = 0;cout << "A() this= " << this << ",value="<<value<<endl; }
A(const A& a) {
cout << "A(A&) this= " << this << endl;
this->value = a.value;
}
void setValue(int value) { this->value = value; }
int getValue() { return this->value; }
};
int main()
{
vector<A> v;
v.reserve(5);
cout << endl << "start create object of A:" << endl;
A a1, a2, a3;
a1.setValue(1);
a2.setValue(2);
a3.setValue(3);
cout << endl << "start push:" << endl;
cout << endl << "start push a1:" << endl;
v.push_back(a1);
cout << endl << "start push a2:" << endl;
v.push_back(a2);
cout << endl << "start push a3:" << endl;
v.push_back(a3);
cout << endl<<"start setValue:" << endl;
a1.setValue(4);
a2.setValue(5);
a3.setValue(6);
cout << endl << "start for:" << endl;
for (auto & a : v)
{
cout << &a << ",value="<<a.getValue()<<endl;
}
}
3.2 运行
start create object of A:
A() this= 00EFF840,value=0
A() this= 00EFF834,value=0
A() this= 00EFF828,value=0
start push:
start push a1:
A(A&) this= 011B60E8
start push a2:
A(A&) this= 011B60EC
start push a3:
A(A&) this= 011B60F0
start setValue:
start for:
011B60E8,value=1
011B60EC,value=2
011B60F0,value=3