C++STL-vector一般使用

文章展示了如何在C++中使用vector容器存储整数和自定义类型数据,通过push_back方法添加元素,并用迭代器和for_each函数进行遍历。同时,示例中包含了对自定义Person类的实例化和插入。
摘要由CSDN通过智能技术生成

vector : 类似数组的一种容器

一般使用和几个遍历方式##

#include <iostream>
#include<string>
#include<vector>
#include<algorithm>

using namespace std;

void myPrint(int& a) {
    cout << a << endl;
}

void test01() {

    vector<int> v;
    v.push_back(10);
    v.push_back(20);
    v.push_back(30);
    v.push_back(40);

    vector<int>::iterator itBegin = v.begin();
    vector<int>::iterator itEnd = v.end();

    //while (itBegin != itEnd)
    //{
    //    cout << *itBegin << endl;
    //    itBegin++;
    //}

    //for (vector<int>::iterator itBegin = v.begin(); itBegin!=itEnd; itBegin++) {
    //    cout << *itBegin << endl;
    //}

    for_each(v.begin(), v.end(), myPrint);


}


int main() {

    test01();

    return 0;
}

vector容器中存放自定义类型数据

//vector容器中存放自定义类型数据
class Person {
public:
    Person(string name, int age) {
        this->name = name;
        this->age = age;
    }
    string name;
    int age;
};


void test02() {
    vector<Person> v;
    Person p1("tom1", 10);
    Person p2("tom2", 12);
    Person p3("tom3", 15);
    Person p4("tom4", 18);

    v.push_back(p1);
    v.push_back(p2);
    v.push_back(p3);
    v.push_back(p4);


    //遍历
    for (vector<Person>::iterator it = v.begin(); it != v.end(); it++) {
        //cout<< (*it).name << " " << (*it).age << endl;
        cout<< it->name << " " << it->age << endl;
    }
}

int main() {

    test02();

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值