3
28
2016
0

stl::各种姿势 基本操作


#include<iostream> #include<algorithm> using namespace std; int main() { int a[9]={1,8,6,3,5,9,2,3,-7}; for(int i=0;i<=8;i++) cout<<a[i]<<' ';cout<<endl; nth_element(a,a+4,a+9); for(int i=0;i<=8;i++) cout<<a[i]<<' ';cout<<endl; cout<<"The 4th element is "<<a[4]<<endl; return 0; }

运行结果:


 

  • 通过调用nth_element(start, start+n, end) 可以使第n大元素处于第n位置(从0开始,其位置是下标为 n的元素),
  • 并且比这个元素小的元素都排在这个元素之前,比这个元素大的元素都排在这个元素之后,
  • 但不能保证他们是有序的
  • 要注意的是,此函数只是将第nth大的元素排好了位置,但并没有返回值。
  • 所以要知道第nth大的元素 还应进行输出
  • 程序实现:
  • next_permutation() 与 prev_permutation()
  • bool next_permutation( iterator start, iterator end);  返回值为布尔型,对字符串进行修改,注意左闭右开。
  • next_permutation()函数功能是得到所有比当前排列大的第一个(最小的)排列。包含在algorithm库中。
  •  

    prev_permutation()函数功能是得到所有比当前排列小的第一个(最大的)排列。包含在STL里。

  •  

    可处理负数

    注意重复元素的情况

     

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
    string str,s;
    cin >> str; s=str;
//从小到大 输出所有比当前排列大的排列 
    while(next_permutation(str.begin(),str.end()))
        cout << str << endl;
    
    puts("————————————————");

//从大到小输出所有比当前排列小的排列
	while(prev_permutation(s.begin(),s.end()))
    	cout << s << endl;
	return 0;
}

很好的遍历函数!


random_shuflle (最小圆覆盖里会用到的一个神奇的东西)

http://blog.csdn.net/cyningsun/article/details/7545679
 

Category: STL | Tags: STL 黑科技 数据生成 | Read Count: 717

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

Host by is-Programmer.com | Power by Chito 1.3.3 beta | Theme: Aeros 2.0 by TheBuckmaker.com