码迷,mamicode.com
首页 > 编程语言 > 详细

STL_算法_依据第n个元素排序(nth_element)

时间:2017-06-28 11:02:27      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:name   ***   tom   排序   c++   cpp   cst   tracking   site   

C++ Primer 学习中。。。

 

简单记录下我的学习过程 (代码为主)


//全部容器适用
nth_element(b,n,e)
nth_element(b,n,e,p)
对照:partition()算法


/**------http://blog.csdn.net/u010579068------**/
#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<list>
#include<functional>
#include<deque>
#include<algorithm>
using namespace std;

/*****************************************
//全部容器适用
nth_element(b,n,e)
nth_element(b,n,e,p)
对照:partition()算法
*****************************************/
/**----------------------------------------------------------------------------------

----------------------------------------------------------------------------------**/
/*************************************************************************************
std::nth_element                    全部排序容器适用                        algorithm
--------------------------------------------------------------------------------------
template <class RandomAccessIterator>
  void nth_element ( RandomAccessIterator first, RandomAccessIterator nth,
                     RandomAccessIterator last );

template <class RandomAccessIterator, class Compare>
  void nth_element ( RandomAccessIterator first, RandomAccessIterator nth,
                     RandomAccessIterator last, Compare comp );
//eg:

*************************************************************************************/


bool myfunction (int i,int j)
{
    return (i>j);
}

int main ()
{
    int m[]= {3,4,5,6,7,2,3,4,5,6,1,2,3,4,5};
    vector<int> myvector(m,m+15);
    vector<int>::iterator it;

//  set some values:
//    for (int i=1; i<10; i++) myvector.push_back(i);   // 1 2 3 4 5 6 7 8 9

//    random_shuffle (myvector.begin(), myvector.end());

    cout << "myvector contains:(原始数据)";
    for (it=myvector.begin(); it!=myvector.end(); ++it)
        cout << " " << *it;

    cout << endl;
//   using default comparison (operator <):
//   cout<<*(myvector.begin()+3)<<endl;
    nth_element (myvector.begin(), myvector.begin()+3, myvector.end());

    cout << "myvector contains:(从小到大)";
    for (it=myvector.begin(); it!=myvector.end(); ++it)
        cout << " " << *it;

    cout << endl;

//  using function as comp
//    cout<<*(myvector.end()-4)<<endl;
//    nth_element (myvector.begin(), myvector.begin()+3, myvector.end(),myfunction);
    nth_element (myvector.begin(), myvector.end()-4, myvector.end(),greater<int>());
    // print out content:
    cout << "myvector contains:(从大到小)";
    for (it=myvector.begin(); it!=myvector.end(); ++it)
        cout << " " << *it;

    cout << endl;

    return 0;
}


STL_算法_依据第n个元素排序(nth_element)

标签:name   ***   tom   排序   c++   cpp   cst   tracking   site   

原文地址:http://www.cnblogs.com/wzjhoutai/p/7088389.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!