📜  删除C++ STL列表中的元素(1)

📅  最后修改于: 2023-12-03 15:22:42.586000             🧑  作者: Mango

删除C++ STL列表中的元素

C++ STL提供的list是一个双向链表,在对数据进行插入、删除操作时十分方便。本文将为大家介绍如何在C++ STL列表中删除元素。

列表元素删除

C++ STL列表提供了几种方式删除元素:

erase()

erase()函数可以删除列表中某个元素:

#include <iostream>
#include <list>

int main() {
   std::list<int> myList = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

   myList.erase(myList.begin()); // 删除第一个元素,即1

   for (auto it = myList.begin(); it != myList.end(); ++it) {
      std::cout << (*it) << " ";
   }
   std::cout << std::endl;

   return 0;
}

上面的代码中,我们调用了erase()函数,通过列表的迭代器指定了要删除的元素。在这个例子中,我们删除了第一个元素,结果输出结果如下:

2 3 4 5 6 7 8 9 10
remove()

remove()函数可以删除列表中某个值:

#include <iostream>
#include <list>

int main() {
   std::list<int> myList = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

   myList.remove(5); // 删除值为5的元素

   for (auto it = myList.begin(); it != myList.end(); ++it) {
      std::cout << (*it) << " ";
   }
   std::cout << std::endl;

   return 0;
}

上面的代码中,我们调用了remove()函数,通过指定要删除的值来删除元素。在这个例子中,我们删除了值为5的元素,结果输出结果如下:

1 2 3 4 6 7 8 9 10
pop_back()和pop_front()

pop_back()函数可以删除列表中的最后一个元素,并返回删除的元素值;pop_front()函数可以删除列表中的第一个元素,并返回删除的元素值。

#include <iostream>
#include <list>

int main() {
   std::list<int> myList = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

   std::cout << myList.back() << std::endl; // 输出10
   myList.pop_back(); // 删除最后一个元素

   std::cout << myList.front() << std::endl; // 输出1
   myList.pop_front(); // 删除第一个元素

   for (auto it = myList.begin(); it != myList.end(); ++it) {
      std::cout << (*it) << " ";
   }
   std::cout << std::endl;

   return 0;
}

上面的代码中,我们调用了pop_back()和pop_front()函数,分别删除了列表中的最后一个元素和第一个元素。在这个例子中,我们删除了值最后一个元素10和第一个元素1,结果输出结果如下:

2 3 4 5 6 7 8 9
总结

C++ STL列表提供了几种方便的方式删除元素。我们可以通过erase()函数删除指定位置的元素、通过remove()函数删除指定值的元素、通过pop_back()和pop_front()函数删除列表中的最后一个元素和第一个元素。在实际开发中,可以根据不同的需求选择适合的方法进行操作。