返回

STL容器操作函数助你高效编程

见解分享

STL容器操作函数简介

STL容器操作函数是一个函数模板,它可以用于操作任何STL容器。这些函数可以用来添加、删除、查找和修改容器中的元素。

几个常用的STL容器操作函数

1. empty

empty函数用于检查容器是否为空。如果容器为空,则返回true;否则,返回false。

vector<int> v;
if (v.empty()) {
  cout << "Vector is empty" << endl;
} else {
  cout << "Vector is not empty" << endl;
}

2. size

size函数用于返回容器中元素的个数。

vector<int> v = {1, 2, 3, 4, 5};
cout << "Size of vector: " << v.size() << endl;

3. front

front函数用于返回容器中第一个元素的引用。

vector<int> v = {1, 2, 3, 4, 5};
cout << "First element of vector: " << v.front() << endl;

4. back

back函数用于返回容器中最后一个元素的引用。

vector<int> v = {1, 2, 3, 4, 5};
cout << "Last element of vector: " << v.back() << endl;

5. assign

assign函数用于将一个容器中的元素复制到另一个容器中。

vector<int> v1 = {1, 2, 3};
vector<int> v2;
v2.assign(v1.begin(), v1.end());
cout << "Contents of v2: ";
for (int i : v2) {
  cout << i << " ";
}
cout << endl;

6. at

at函数用于访问容器中指定位置的元素。

vector<int> v = {1, 2, 3, 4, 5};
cout << "Element at index 2: " << v.at(2) << endl;

7. insert

insert函数用于在容器中指定位置插入元素。

vector<int> v = {1, 2, 3, 4, 5};
v.insert(v.begin() + 2, 10);
cout << "Contents of v after insertion: ";
for (int i : v) {
  cout << i << " ";
}
cout << endl;

8. erase

erase函数用于删除容器中指定位置的元素。

vector<int> v = {1, 2, 3, 4, 5};
v.erase(v.begin() + 2);
cout << "Contents of v after deletion: ";
for (int i : v) {
  cout << i << " ";
}
cout << endl;

9. clear

clear函数用于删除容器中的所有元素。

vector<int> v = {1, 2, 3, 4, 5};
v.clear();
cout << "Size of vector after clearing: " << v.size() << endl;

10. push_back

push_back函数用于在容器的末尾添加一个元素。

vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
cout << "Contents of v: ";
for (int i : v) {
  cout << i << " ";
}
cout << endl;

11. pop_back

pop_back函数用于删除容器末尾的元素。

vector<int> v = {1, 2, 3, 4, 5};
v.pop_back();
cout << "Contents of v after popping back: ";
for (int i : v) {
  cout << i << " ";
}
cout << endl;

结语

STL容器操作函数是C++标准模板库中的一个重要组成部分,它提供了各种用于操作容器的函数,使编程人员可以轻松地处理数据结构。本文介绍了几个常用的STL容器操作函数,包括empty、size、front、back、assign、at、insert、erase、clear、push_back和pop_back。希望这些函数能够帮助您编写更有效、更健壮的C++程序。