#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;
}
分类:
C++基础第一卷
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探