list容器

发布时间 2023-12-06 22:10:06作者: 牟兆迪

3.7.4 list 大小操作

功能描述:

  • 对list容器的大小进行操作

 

函数原型:

  • size(); //返回容器中元素的个数

  • empty(); //判断容器是否为空

  • resize(num); //重新指定容器的长度为num,若容器变长,则以默认值填充新位置。

    //如果容器变短,则末尾超出容器长度的元素被删除。

  • resize(num, elem); //重新指定容器的长度为num,若容器变长,则以elem值填充新位置。

    //如果容器变短,则末尾超出容器长度的元素被删除。

 

示例:

#include <list>

void printList(const list<int>& L) {

for (list<int>::const_iterator it = L.begin(); it != L.end(); it++) {
cout << *it << " ";
}
cout << endl;
}

//大小操作
void test01()
{
list<int>L1;
L1.push_back(10);
L1.push_back(20);
L1.push_back(30);
L1.push_back(40);

if (L1.empty())
{
cout << "L1为空" << endl;
}
else
{
cout << "L1不为空" << endl;
cout << "L1的大小为: " << L1.size() << endl;
}

//重新指定大小
L1.resize(10);
printList(L1);

L1.resize(2);
printList(L1);
}

int main() {

test01();

system("pause");

return 0;
}

总结:

  • 判断是否为空 --- empty

  • 返回元素个数 --- size

  • 重新指定个数 --- resize

 

 

 

 

 

3.7.5 list 插入和删除

功能描述:

  • 对list容器进行数据的插入和删除

 

函数原型:

  • push_back(elem);//在容器尾部加入一个元素

  • pop_back();//删除容器中最后一个元素

  • push_front(elem);//在容器开头插入一个元素

  • pop_front();//从容器开头移除第一个元素

  • insert(pos,elem);//在pos位置插elem元素的拷贝,返回新数据的位置。

  • insert(pos,n,elem);//在pos位置插入n个elem数据,无返回值。

  • insert(pos,beg,end);//在pos位置插入[beg,end)区间的数据,无返回值。

  • clear();//移除容器的所有数据

  • erase(beg,end);//删除[beg,end)区间的数据,返回下一个数据的位置。

  • erase(pos);//删除pos位置的数据,返回下一个数据的位置。

  • remove(elem);//删除容器中所有与elem值匹配的元素。

 

 

示例:

#include <list>

void printList(const list<int>& L) {

for (list<int>::const_iterator it = L.begin(); it != L.end(); it++) {
cout << *it << " ";
}
cout << endl;
}

//插入和删除
void test01()
{
list<int> L;
//尾插
L.push_back(10);
L.push_back(20);
L.push_back(30);
//头插
L.push_front(100);
L.push_front(200);
L.push_front(300);

printList(L);

//尾删
L.pop_back();
printList(L);

//头删
L.pop_front();
printList(L);

//插入
list<int>::iterator it = L.begin();
L.insert(++it, 1000);
printList(L);

//删除
it = L.begin();
L.erase(++it);
printList(L);

//移除
L.push_back(10000);
L.push_back(10000);
L.push_back(10000);
printList(L);
L.remove(10000);
printList(L);
   
   //清空
L.clear();
printList(L);
}

int main() {

test01();

system("pause");

return 0;
}

总结:

  • 尾插 --- push_back

  • 尾删 --- pop_back

  • 头插 --- push_front

  • 头删 --- pop_front

  • 插入 --- insert

  • 删除 --- erase

  • 移除 --- remove

  • 清空 --- clear

  •