c++vector push_back pop_back
时间: 2023-09-01 14:11:23 浏览: 130
C++ 的 vector 类是一个动态数组,可以在运行时动态增加或减少其大小。可以使用 push_back() 函数将元素添加到 vector 的末尾,使用 pop_back() 函数将 vector 的末尾元素删除。示例代码如下:
```c++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// 创建一个空的 vector
vector<int> v;
// push_back() 函数添加元素到 vector 的末尾
v.push_back(1);
v.push_back(2);
v.push_back(3);
// 输出 vector 中的元素
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
// pop_back() 函数删除 vector 的末尾元素
v.pop_back();
// 输出 vector 中的元素
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果:
```
1 2 3
1 2
```
相关问题
c++中back()、push_back()与pop_back()函数
在C++中,back()、push_back()和pop_back()是vector容器的成员函数。
1. back()函数用于返回vector容器的最后一个元素。
```c++
#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector {1, 2, 3, 4, 5};
std::cout << "The last element of the vector is: " << myVector.back() << std::endl;
return 0;
}
```
输出结果为:
```
The last element of the vector is: 5
```
2. push_back()函数用于在vector容器的末尾添加一个元素。
```c++
#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector {1, 2, 3, 4};
myVector.push_back(5);
std::cout << "The new vector is: ";
for (auto i : myVector) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
```
输出结果为:
```
The new vector is: 1 2 3 4 5
```
3. pop_back()函数用于删除vector容器的最后一个元素。
```c++
#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector {1, 2, 3, 4, 5};
myVector.pop_back();
std::cout << "The new vector is: ";
for (auto i : myVector) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
```
输出结果为:
```
The new vector is: 1 2 3 4
```
pop_back和push_back
push_back和pop_back都是容器vector的操作函数。push_back函数用于在容器末尾插入新的元素,而pop_back函数用于删除容器末尾的元素。具体来说,push_back将一个新元素添加到vector的末尾,而pop_back则将容器末尾的元素删除。使用这两个函数可以方便地进行向vector中添加元素和删除元素的操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [020 通过链表学Rust之push_back和pop_back等](https://blog.csdn.net/lcloveyou/article/details/122158348)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [C++中push_back与pop_back的用法](https://blog.csdn.net/qq_32867925/article/details/104851126)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文