C++STL程序:全排列,删除、插入元素。

来源:互联网 发布:ubuntu iso 编辑:程序博客网 时间:2024/06/06 05:46

写两个STL程序,并对他们进行分析设计,结果如下:

1.#include <iostream>

#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int a[6]={5,9,12,60,62,65};
vector<int> vec(a,a+6);//创建vector
vector<int>::size_type i;
cout<<"递增数组:";
for(i=0;i<vec.size();i++)//输出vector中的所有元素
{
cout<<vec[i]<<' ';
}
cout<<endl;
cout<<"最大值:";
make_heap(vec.begin(),vec.end());
cout<<vec[0];//找出最大值
cout<<endl;
cout<<"移除最大值后输出序列:";
pop_heap(vec.begin(),vec.end());
vec.pop_back();
for(i=0;i<5;i++)
{
cout<<vec[i]<<' ';
}
cout<<endl;
cout<<"在序列头部插入元素后的序列:";
vec.insert(vec.begin(),90);
for(i=0;i<=5;i++)
{
cout<<vec[i]<<' ';
}
cout<<endl;
return 0;
}






2.#include<iostream> 
#include<algorithm>
using namespace std;
const int N = 4;
int arr[N] = {1,2,3,4};
int main() 

 do{ 
for(int i=0; i < N; i++) 
printf("%d ",arr[i]); 
putchar('\n'); 
}while(next_permutation(arr,arr+N));
return 0; 
}




实验步骤:
(1)1.由于程序用到STL中的vector容器,所以需要加上头文件#include <vector>
2.先定义一个数组a[6],然后创建有6个整型元素的vector容器,代码如下:
vector<int> vec(a,a+6);//创建vector
然后输出这组数
3.利用make_heap(vec.begin(),vec.end())函数找出这组数的最大值,pop_heap(vec.begin(),vec.end())函数移除最大值,移除最大值后输出这组数,用vec.insert(vec.begin(),90)函数在序列头部插入元素,最后输出这个序列
4.编写程序,上机运行调试
5.查看结果
(2)1.next_permutation是STL中专门用于排列的函数,运行需要包含头文件#include<algorithm>
2.定义一个整型数组arr[N],这里的N定义为4,const int N = 4.利用prev_permutation(arr,arr+N)将arr里的数据按降序排列
5.编写程序,上机运行调试
6.查看结果
                       




实验结果:
1.递增数组:5 9 12 60 62 65
最大值:65
移除最大值后输出序列:62 60 12 5 9
在序列头部插入元素后的序列:90 62 60 12 5 9
2.
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1