这一篇主要讲一下C++里面常用到的两个容器vector和map。
vector相当于一个动态数组。
map是一个键值对的容器,下面我们直接用代码来了解一些这两个容器的常用方法。
#include<iostream>
#include<vector>
using namespace std;
int main(){
//1.变量的声明
vector<int> vec; //vec相当于一个存放int型数据的可变长数组
//2.push_back()在数组的最后添加一个元素,分别添加4,5,6三个元素
vec.push_back(4);
vec.push_back(5);
vec.push_back(6);
//3.pop_back()去掉数组的最后一个元素,将6从数组中删除
vec.pop_back();
//4.size()函数获取当前容器的大小,此时容器内有4,5两个元素,所以size为2
cout << vec.size() << endl;
//5.at访问某一位置上的值
cout << vec.at(1) << endl;
//6.使用迭代器遍历访问元素
vector<int>::iterator it;
for (it = vec.begin(); it != vec.end(); it++)
cout << *it << endl;
return 0;
}#include<iostream>
#include<string>
#include<map> //头文件包含
//map类型一个键只能对应一个值,multimap允许一个键对应多个值
using namespace std;
int main(){
//1.map型变量的定义
map<string, int> student;
//2.插入数据
student["Tom"] = 25;
student.insert(map<string, int>::value_type("Jack", 22));
student.insert(pair<string, int>("Lucy", 23));
//3.查找数据和修改数据
int age = student["Tom"];
cout << "the age of Tom is:" << age << endl;
student["Tom"] = 18;
//4.删除数据
student.erase("Tom");
//5.容器大小
cout << student.size() << endl;
//6.判断容器是否为空
cout << student.empty() << endl;
//7.迭代数据
map<string, int>::iterator it;
for (it = student.begin(); it != student.end(); it++){
cout << it->first << " " << it->second << endl; //不包含头文件string这里无法直接输出it->first
}
//8.清空容器
student.clear();
return 0;
}
本文通过示例代码详细介绍了C++ STL中的两种重要容器:动态数组vector及键值对容器map的基本操作,包括元素的添加、访问、删除等。
13万+

被折叠的 条评论
为什么被折叠?



