用C++编写一个程序,使用vector容器来实现一个整数列表。程序需要实现以下功能: 添加整数到列表末尾 在指定位置插入整数 删除指定位置的整数 显示列表中的所有整数 要求使用函数来实现每个功能,并在下面给出的主函数中进行测试(即要求主函数如下,不能变更任何信息)。 int main() { vector<int> numbers; // 添加整数到列表末尾 addInteger(numbers, 1); addInteger(numbers, 2); addInteger(numbers, 3); // 在指定位置插入整数,第二个参数是数值,第3个参数是位置 insertInteger(numbers, 4, 1); // 删除指定位置的整数 deleteInteger(numbers, 2); // 显示列表中的所有整数 displayIntegers(numbers); return 0; }
时间: 2024-03-07 11:48:23 浏览: 39
好的,以下是使用vector容器实现整数列表的程序,实现了添加整数到列表末尾、在指定位置插入整数、删除指定位置的整数、显示列表中的所有整数的功能:
```c++
#include <iostream>
#include <vector>
using namespace std;
// 添加整数到列表末尾
void addInteger(vector<int>& numbers, int num) {
numbers.push_back(num);
}
// 在指定位置插入整数
void insertInteger(vector<int>& numbers, int num, int pos) {
if (pos < 0 || pos > numbers.size()) {
cout << "Invalid position!" << endl;
} else {
numbers.insert(numbers.begin() + pos, num);
}
}
// 删除指定位置的整数
void deleteInteger(vector<int>& numbers, int pos) {
if (pos < 0 || pos >= numbers.size()) {
cout << "Invalid position!" << endl;
} else {
numbers.erase(numbers.begin() + pos);
}
}
// 显示列表中的所有整数
void displayIntegers(vector<int>& numbers) {
cout << "Integers in the list:" << endl;
for (int i = 0; i < numbers.size(); i++) {
cout << numbers[i] << " ";
}
cout << endl;
}
int main() {
vector<int> numbers;
// 添加整数到列表末尾
addInteger(numbers, 1);
addInteger(numbers, 2);
addInteger(numbers, 3);
// 在指定位置插入整数,第二个参数是数值,第3个参数是位置
insertInteger(numbers, 4, 1);
// 删除指定位置的整数
deleteInteger(numbers, 2);
// 显示列表中的所有整数
displayIntegers(numbers);
return 0;
}
```
运行结果:
```
Integers in the list:
1 4 3
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)