c++中的vector和queue

vector

  1. 宏观定义:
    a sequence container that encapsulates dynamic size arrays.
  2. 与数组的区别:
    Vectors usually occupy more space than static arrays, because more memory is allocated to handle future growth. This way a vector does not need to reallocate each time an element is inserted, but only when the additional memory is exhausted.
  3. Create a vector containing integers:
    声明一个vector变量的语法为vector<T> vec,其中T代表存储的元素类型,vec为vector变量的名字
#include <vector>
#include <iostream>
using namespace std;

int main(){
    vector<int> v;  // 创建一个整数vector

    // 用`push_back`方法将元素添加到向量末尾
    v.push_back(42);
    v.push_back(33);
    v.push_back(2);
    v.push_back(12);

    // 可通过[]或at()来访问向量中的元素
    int x = v[0];  // 访问第一个元素
    int y = v.at(1);  // 访问第二个元素
    cout << x << endl;
    cout << y << endl;

    // 可用size()方法来获取向量中元素的数量
    int size = v.size();
    cout << size;

    // 遍历vector:可使用for循环
    for (auto element : v){
        cout<<element<<"\n";
    }

    // 使用`pop_back()`方法删除向量中的最后一个元素
    v.pop_back();
    // 遍历vector:可使用for循环
    for (auto element : v){
        cout<<element<<"\n";
    }

    // 清空vector:可使用`clear()`方法
    v.clear();
    // 遍历vector:可使用for循环
    for (auto element : v){
        cout<<element<<"\n";
    }
}

queue

#include<iostream>
#include<queue>
using namespace std;
int main()
{
	queue<int> q; //定义一个数据类型为int的queue 
	q.push(1); //向队列中加入元素1 
	q.push(2); //向队列中加入元素2
	q.push(3); //向队列中加入元素3 
	q.push(4); //向队列中加入元素4 
	cout<<"将元素1、2、3、4一一加入队列中后,队列中现在的元素为:1、2、3、4"<<endl;
	cout<<"队列中的元素个数为:"<<q.size()<<endl;
	//判断队列是否为空 
	if(q.empty())
	{
		cout<<"队列为空"<<endl;
	}
	else
	{
		cout<<"队列不为空"<<endl;
	}
	cout<<"队列的队首元素为:"<<q.front()<<endl;
	//队列中的队首元素出队 
	q.pop();
	cout<<"将队列队首元素出队后,现在队列中的元素为2、3、4"<<endl;		
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值