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//✖
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/607290.html