std::nth_elelment 정렬
본문http://blog.csdn.net/readzw/article/details/8746108
[cpp] view plain copy print ?
template
void nth_element(_RanIt _First, _RanIt _Nth, _RanIt _Last)
template<class _RanIt, class _Pr> inline
void nth_element(_RanIt _First, _RanIt _Nth, _RanIt _Last, _Pr _Pred)
template<class _RanIt> inline
void nth_element(_RanIt _First, _RanIt _Nth, _RanIt _Last)
이 함수 의 역할 은 교체 기 를 가리 키 는 종 이다.First tolast 사이 의 원 소 를 2 분 정렬 하여Nth 는 분계 이 고 앞 은 모두Nth 는 작고(크다),뒤 는 모두 크다(작다).하지만 두 단락 내 에는 질서 가 없다.
특히 앞의 k 개의 최대(최소)요 소 를 찾 는 데 적용 된다.
예 를 들 면:
[cpp] view plain copy print ?
vector
// calc the value of temp;
vector<int> temp;
//
// calc the value of temp;
//
nth_element(temp.begin(), temp.begin()+10,temp.end());
//
구조 체 를 사용자 정의 방식 으로 정렬 하려 면 첫 번 째 방법 을 사용 할 수 있 습 니 다.
먼저 bool 형식 으로 돌아 가 는 비교 함 수 를 정의 한 다음 함수 이름 을 매개 변수 로 입력 합 니 다.
예 를 들 어 현재 가격 에 따라 가장 비 싼 10 권 의 책 을 골 라 달라 고 요구 하고 있다.
[cpp] view plain copy print ?
bool prizeCompare(const CBook &b1, const CBook &b2)
return b1.prize>b2.prize;
가장 비 싼 책 10 권 을 골라내다
books.resize(10);
bool prizeCompare(const CBook &b1, const CBook &b2)
{
return b1.prize>b2.prize;
}
// ......
vector<CBook> books;
// 10
std::nth_element(books.begin(), books.begin()+10,books.end(), prizeCompare);
books.resize(10);
한 걸음 더 깊이,지금 은 물리학 의 책 만 정렬 하고,현재 하나의 vector
코드 는 다음 과 같 습 니 다:
[cpp] view plain copy print ?
struct Cmp{
Cmp(const std::vector
{
}
}
vector
for(int i=0;i
physics.resize(10);
struct Cmp{
std::vector<Book> _list;
Cmp(const std::vector<Book> &_books):_list(_books){}
bool operator()(int idx1,int idx2)
{
return _list[idx1].prize>_list[idx2].prize;
}
}
//......
vector<CBook> books;
vector<int> physics;
for(int i=0;i<books.size();i++){ if(books[i].category == PHYSICS) physics.push_back(i);
}
//......
std::nth_element(physics.begin(), physics.begin()+10,physics.end(), Cmp(books));
physics.resize(10);
[cpp] view plain copy print ?
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.