设为首页 加入收藏

TOP

C++ vector和iterator简单用法(代码实例)
2018-05-21 15:48:16 】 浏览:167
Tags:vector iterator 简单 用法 代码 实例

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;
}

使用iterator和使用下标效果是一样的。

2.基本数据类型

使用对象名取地址,加入vector中

 vector<string*> a;
 string str = "hello";
 a.push_back(&str);

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//?
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇c++ &符号地址获取方式 下一篇C++ 的接雨水问题及题解分析

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目