C++ vector和iterator简单用法(转)
程序员文章站
2022-07-14 12:30:14
...
转自:https://blog.csdn.net/qq_38786209/article/details/80303190
vector是动态可变数组,可以添加int、double、自定义的类
1.int示例:
#incldue<vector>
vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
for(vector<int>::iterator iter = a.begin();iter != a.end(); ++iter)
{
cout << *iter << endl;
}
for(int i=0;i<a.size();i++)
{
cout << a[i]<<endl;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
使用iterator和使用下标效果是一样的。
2.基本数据类型
使用对象名取地址,加入vector中
vector<string*> a;
string str = "hello";
a.push_back(&str);
- 1
- 2
- 3
3.自定义类
上面的方法有个弊端,就是必须写不同的对象名,才能区分对象。如果想要在循环里不断新建和消除对象,就不方便。
解决方法:
假设我们有个类叫test_class,想要每次新建一个类,构造函数参数分别为x,y,并加入叫a的vector里
vector<test_class *> a;//该类的指针
test_class *tes = NULL;//声明一个test_class类型的指针
tes = new test_class(x,y);//申请一块新的内存空间,并初始化该对象,指针指向该对象
a.push_back(tes);
//在用到该对象时,应该使用指针的->,而不是用对象名.
tes->x;//✔
tes.x//✖
上一篇: vector的简单用法
下一篇: Java数据结构:循环队列的简单实现