动态数组:有些时候想开一个数组,但是却不知道应该开多大长度的数组合适,因为我们需要用到的数组可能会根据情况变动。这时候我们就需要用到动态数组。
C++中动态数组写作vector。
要使用vector,需要添加头文件 #include<vector>
定义和初始化:C++中定义一个动态数组为 vector<T> t T为类型,t为名称。
插入元素:通过push_back()方法插入元素。
获取长度并访问元素:通过size()方法获取长度,通过[]操作动态数组中的元素。
修改元素:通过[]赋值。
演示:
#include
#include
using namespace std;
int main()
{
vector
t1; //创建一个int类型的动态数组
for (int i = 0; i < 4; i++)
{
t1.push_back(i); //插入元素
}
cout << t1[1] << endl; //操作数组中元素
t1[2] = 3; //修改数组中元素
t1.erase(t1.begin()); //移除头元素
return 0;
}
Map:C++中map容器提供一个键值对(key/value)容器,map与multimap差别仅仅在于multiple允许一个键对应多个值。需要包含头文件map。对于迭代器来说,可以修改实值,而不能修改key。Map会根据key自动排序。
要使用map,需要添加头文件 #include<map>
map的使用有多种方法
演示:
#include
#include
集合set:集合是由一些不重复的数据组成的。
演示:
#include
#include
#include
using namespace std;
int main()
{
set
city; //定义
city.insert("TangShan");
city.insert("BeiJing"); //插入,注意当向集合中插入一个已存在的数据,不会产生任何效果。
city.erase("TangShan"); //删除数据
if (city.count("BeiJing")) //查找,如果存在返回1
printf("存在北京这个城市\n");
for (set
::iterator it = city.begin(); it != city.end(); ++it) //用迭代器遍历集合中的元素 { cout << (*it) << endl; } return 0; }
要使用stack,需要添加头文件 #include<stack>
定义和初始化:C++中定义一个栈为 stack<T> t T为类型,t为名称。
入栈:通过push()方法。
获取栈顶元素:通过top()方法。
出栈:通过pop()方法。
判空:通过empty()方法。
演示:
#include
#include
using namespace std;
int main()
{
stack
s; //创建一个int类型的栈
s.push(1);
s.push(2); //入栈
cout << s.top() << endl; //获取栈顶元素
s.pop(); //出栈
return 0;
}
要使用queue,,需要添加头文件 #include<queue>
定义和初始化:C++中定义一个队列为 queue <T> t T为类型,t为名称。
入队:通过push()方法。
获取队首元素:通过front()方法。
出队:通过pop()方法。
判空:通过empty()方法。
演示:#include
#include
using namespace std;
int main()
{
queue
q; //创建一个int类型的队列
q.push(1);
q.push(2); //入队
cout << q.front() << endl; //获取队首元素
q.pop(); //出队
return 0;
}