用c++定义一个空的list,将用户输入的数组a[10]的10个数插入到list中,在list头部插入数b,用迭代器遍历list并输出其中的元素值。然后将list从大到小排序,删除list尾部的元素,用迭代器遍历list并输出其中的元素值。最后将list清空。
时间: 2023-08-18 12:09:53 浏览: 36
以下是C++代码实现:
```c++
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> mylist; // 定义空的list
int a[10];
cout << "请输入数组a的10个元素:" << endl;
for (int i = 0; i < 10; i++) {
cin >> a[i];
mylist.push_back(a[i]); // 将数组元素插入到list尾部
}
int b;
cout << "请输入数b:" << endl;
cin >> b;
mylist.push_front(b); // 在list头部插入数b
cout << "遍历list并输出其中的元素值:" << endl;
for (list<int>::iterator it = mylist.begin(); it != mylist.end(); it++) {
cout << *it << " ";
}
cout << endl;
mylist.sort(); // 从小到大排序
mylist.pop_back(); // 删除list尾部的元素
cout << "排序后,遍历list并输出其中的元素值:" << endl;
for (list<int>::iterator it = mylist.begin(); it != mylist.end(); it++) {
cout << *it << " ";
}
cout << endl;
mylist.clear(); // 清空list
return 0;
}
```
运行结果示例:
```
请输入数组a的10个元素:
1 2 3 4 5 6 7 8 9 10
请输入数b:
0
遍历list并输出其中的元素值:
0 1 2 3 4 5 6 7 8 9 10
排序后,遍历list并输出其中的元素值:
0 1 2 3 4 5 6 7 8 9
```