posts - 137,comments - 0,views - 40818
复制代码
#include <iostream>
#include <string>
#include <stdlib.h>
#include <vector>
//#include <algorithm>

using namespace std;
//vector容器的简单应用
void demo1() {
    vector<int> v1;
    v1.push_back(4);
    v1.push_back(2);
    v1.push_back(4);
    v1.push_back(3);
    v1.push_back(4);

    cout << "v1中的元素个数:" << v1.size() << endl;
    cout << "v1中保存的元素:" << endl;
    //第一种方式,数组访问
    //for (int i = 0; i < v1.size(); i++) {
    //    cout << v1[i] << endl;
    //}
    //第二种方式,迭代器访问
    vector<int>::iterator is = v1.begin();
    for (; is != v1.end(); is++) {
        cout << *is << endl;
    }
    //统计容器中某个元素的个数
    int rcount = count(v1.begin(), v1.end(), 4);
    cout << "v1中数值为4的元素一共有" << rcount << "" << endl;
}
class Student {
public:
    Student(int age, const char* name) {
        this->age = age;
        strncpy_s(this->name, name, 64);
        cout << "调用了构造函数" << endl;
    }
    Student(const Student& s) {
        this->age = s.age;
        strncpy_s(this->name, s.name, 64);
        cout << "调用了拷贝构造函数" << endl;
    }
    ~Student() {
        cout << "调用了析构函数" << endl;
    }
    int age;
    char name[64];
};
void demo2() {
    vector<Student *> s; //使用指针提高效率,此处不可用引用!
    Student s1(12,"小王");
    Student s2(23,"大王");
    s.push_back(&s1);
    s.push_back(&s2);
    //第一种方式,数组访问
    /*for (int i = 0; i < s.size(); i++) {
        cout << (*s[i]).age<<":"<<(*s[i]).name << endl;
    }*/
    //第二种方式,迭代器访问
    vector<Student *>::iterator it = s.begin();
    for (; it != s.end(); it++) {
        cout << (**it).name<<":"<<(**it).age << endl;
    }
}
int main() {
    demo1();
    cout << endl;
    demo2();
    
    system("pause");
    return 0;
}
复制代码

posted on   wshidaboss  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示