首页 > 代码库 > vector 排序
vector 排序
http://classfoo.com/ccby/article/cIBahI
排序 sort 同 stable_sort
#include <vector>#include <algorithm>#include <functional> // For greater<int>()#include <iostream>int main(){ vector <int> foo; vector <int>::iterator Iter1; for (int ii = 0; ii <= 5; ii++){ foo.push_back(2 * ii + 1); } // 按升序排序,使用默认的二元谓词函数 sort(foo.begin(), foo.end()); // 按降序排序,提供二元谓词函数 sort(foo.begin(), foo.end(), greater<int>()); // 使用自定义的二元谓词函数 sort(foo.begin(), foo.end(), [](int elem1, int elem2){return elem1 > elem2; }); for (Iter1 = foo.begin(); Iter1 != foo.end(); Iter1++) cout << *Iter1 << " "; return 0;}
部分排序,随机数,generate函数
#include <vector>
#include <algorithm> // for generate、partial_sort
#include <functional>
#include <iostream>
#include <cstdlib> // std::rand, std::srand
#include <ctime> // std::time
namespace ClassFoo{
int RandomNumber() { return (std::rand() % 100); }
void PartialSort1()
{
std::srand(unsigned(std::time(0)));
std::vector<int> foo(15);
std::generate(foo.begin(), foo.end(), RandomNumber);
// 部份排序前七个元素
std::partial_sort(foo.begin(), foo.begin() + 7, foo.end());
std::vector <int>::iterator Iter1;
for (Iter1 = foo.begin(); Iter1 != foo.end(); Iter1++)
std::cout << *Iter1 << " ";
std::cout << std::endl;
}
}
int main(void)
{
ClassFoo::PartialSort1();
return 0;
}
vector 排序