容器的头部与尾部元素的插入(C++)
在对数据进行排序时,对于任意选取的某一元素,大于该元素的在其前面,小于该元素的则在其后面。常用的vector容器没有这个功能。C++中deque可以对容器进行双向操作,示例如下:(1)非结构体的操作:#include<deque>#include<iostream>using namespace std;void main(){deque<double> arr
·
在对数据进行排序时,对于任意选取的某一元素,大于该元素的在其前面,小于该元素的则在其后面。常用的vector容器没有这个功能。C++中deque可以对容器进行双向操作,使用push_front()与push_back(),示例如下:
(1)非结构体的操作:
#include<deque>
#include<iostream>
using namespace std;
void main()
{
deque<double> arr;
arr.push_front(1);
arr.push_front(2);
arr.push_front(3);
arr.push_back(0);
arr.push_back(-1);
arr.push_front(4);
arr.push_front(5);
arr.push_back(-2);
arr.push_back(-3);
for (int i = 0; i < arr.size(); i++)
{
cout << arr[i] << "\t";
}
cout << endl << "finish" << endl;
system("pause");
}
可以看到经过排序后,数组元素是按照降序输出。
(2)结构体的操作:
#include<deque>
#include<iostream>
using namespace std;
void main()
{
struct point
{
double x;
double y;
double z;
point(double a, double b, double c)
{
this->x = a;
this->y = b;
this->z = c;
}
};
point p1(1, 1, 1), p2(2, 2, 2), p3(3, 3, 3), p4(0, 0, 0), p5(-1, -1, -1), p6(4, 4, 4), p7(5, 5, 5), p8(-2, -2, -2), p9(-3, -3, -3);
deque<point> arr;
arr.push_front(p1);
arr.push_front(p2);
arr.push_front(p3);
arr.push_back(p4);
arr.push_back(p5);
arr.push_front(p6);
arr.push_front(p7);
arr.push_back(p8);
arr.push_back(p9);
for (int i = 0; i < arr.size(); i++)
{
cout << arr[i].x << "\t" << arr[i].y << "\t" << arr[i].z << endl;
}
cout << endl << "finish" << endl;
system("pause");
}
仍是按照降序的方式输出
更多推荐
已为社区贡献1条内容
所有评论(0)