list容器的大小操作
大小操作#include<iostream>using namespace std;#include<list>//防止数据修改,只做读取操作void print(const list<int>& L){for (list<int>::const_iterator it = L.begin(); it != L.end(); it++){co
·
大小操作
#include<iostream>
using namespace std;
#include<list>
//防止数据修改,只做读取操作
void print(const list<int>& L)
{
for (list<int>::const_iterator it = L.begin(); it != L.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
//list的大小操作
void test()
{
//默认构造
list<int> L1 = {5,2,0,1};
L1.push_back(3);
L1.push_back(1);
L1.push_back(4);
print(L1);
//判断容器是否为空
if (L1.empty())
{
cout << "容器为空!" << endl;
}
else {
cout << "容器不为空" << endl;
cout << "容器中元素个数:" << L1.size() << endl;
}
//重新指定大小,如果新指定大小大于原来的元素个数,就用默认值0填充新位置
L1.resize(10);
print(L1);
//如果指定大小小于原来的元素个数,就讲多出的元素删除
L1.resize(3);
print(L1);
//可以用resize的重载版本,自己指定多出来的新位置的默认值
L1.resize(6,521);
print(L1);
}
int main()
{
test();
system("pause");
return 0;
}

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)