vector
一 用法
1.1 插入数据
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Man
{
public:
Man(int age) { this->age = age; }
private:
int age;
}
int main()
{
vector<int> data;
data.push_back(1); //尾部插入
data.push_back(5);
data.push_back(9);
for (int i = 0; i < data.size(); i++)
{
cout << data[i] << " ";
}
cout << endl;
vector<string> str;
string s1 = "I";
string s2 = "love";
string s3 = "you";
str.push_back(s1);
str.push_back(s2);
str.push_back(s3);
for (int i = 0; i < str.size(); i++)
{
cout << str[i] << " ";
}
cout << endl;
vector<Man> mans;
mans.push_back(Man(18)); // 这里push_back的是新对象
return 0;
}
1.2 删除数据
int main()
{
string s1 = "张三";
string s2 = "李四";
string s3 = "王五";
string s4 = "赵六";
vector<string*> friends;
friends.push_back(&s1);
friends.push_back(&s2);
friends.push_back(&s3);
friends.push_back(&s4);
//friends.begin() 返回一个迭代器,指向第一个成员的位置
//friends.end() 返回一个迭代器,指向最后一个成员的下一个位置
for (auto it = friends.begin(); it != friends.end();)
{
if (*it == &s3) // 删除王五
{
//friends.erase() 返回一个迭代器,指向下一个成员
it = friends.erase(it);
}
else
{
it++;
}
}
for (int i = 0; i < friends.size(); i++)
{
cout << *(friends[i]) << endl;
}
return 0;
}
如果将上面删除代码修改为下面代码,会报错
for (auto it = friends.begin(); it != friends.end();it++)
{
if (*it == &s3) // 删除王五
{
friends.erase(it);
}
}
二 常见错误
注意:vector是值拷贝,如果是指针的话,是址拷贝 vector<Man*> mans;
#include <iostream>
#include <vector>
using namespace std;
class Man
{
public:
Man() {}
void play()
{
count += 10;
cout << "I am playing ...." << endl;
}
int getDrinkCount() const
{
return count;
}
private:
int count = 0; //一共喝了多少杯酒
};
int main(void)
{
Man zhangFei, guanYu, liuBei;
vector<Man> men; //这里是值拷贝,想要址拷贝,需要定义成指针类型 vector<Man*> men;
// push_back 是把参数的值,拷贝给 vector
// men[0]的值和 liubBei 是相同的,但是,是两个不同的对象
men.push_back(liuBei);
men.push_back(guanYu);
men.push_back(zhangFei);
men[0].play();
cout << men[0].getDrinkCount() << endl; //10
cout << liuBei.getDrinkCount() << endl; //0
system("pause");
return 0;
}