[cpp]
#include
#include
#include
#include
#include
struct Vec2D
{
float x;
float y;
Vec2D() : x(0.f), y(0.f)
{
}
Vec2D(float fx, float fy) : x(fx), y(fy)
{
}
};
std::ostream& operator << (std::ostream &out, const Vec2D &val)
{
return out<<"("<
}
struct Vec3D
{
float x;
float y;
float z;
Vec3D() :x(0.f), y(0.f), z(0.f)
{
}
Vec3D(float fx, float fy, float fz) : x(fx), y(fy), z(fz)
{
}
float length_squared() const
{
return x * x + y * y + z * z;
}
float length() const
{
return sqrtf(length_squared());
}
bool operator < (const Vec3D &rhs)
{
return length_squared() < rhs.length_squared();
}
};
std::ostream& operator << (std::ostream &out, const Vec3D &val)
{
return out<<"("<
}
template
void print_vector(const std::vector &v)
{
using std::cout;
using std::endl;
for (std::vector::const_iterator iter = v.begin(); iter != v.end(); ++iter)
{
cout<<(*iter)<<"\t";
}
cout<
}
// vector排序方法,这里按绝对值由小到大排序
static bool sort_comp_int(int elem1, int elem2)
{
return abs(elem1) < abs(elem2);
}
// vector排序方法,这里先按x由大到小排序,如果x相同再按y由小到大排序
static bool sort_comp_Vec2D(const Vec2D &elem1, const Vec2D &elem2)
{
if (elem1.x > elem2.x)
return true;
else if (elem1.x == elem2.x)
return elem1.y < elem2.y;
return false;
}
int main(int argc, char **argv)
{
using std::cout;
using std::cin;
using std::endl;
cout<<"========== sort std::vector ==============="<
std::vector vi;
vi.push_back(3);
vi.push_back(-4);
vi.push_back(1);
vi.push_back(5);
cout<<"before sort: "<
print_vector(vi);
// 使用默认的排序算法(operator <)由小到大排序
std::sort(vi.begin(), vi.end());
cout<<"sort default: "<
print_vector(vi);
// 使用 STL 提供的由大到小的排序算法
std::sort(vi.begin(), vi.end(), std::greater());
cout<<"sort greater: "<
print_vector(vi);
// 使用自定义的排序算法
std::sort(vi.begin(), vi.end(), sort_comp_int);
cout<<"sort user defined: "<
print_vector(vi);
//////////////////////////////////////////////////////////////////////////
cout<<"========== sort std::string ==============="<
std::string s = "Hello, world!";
cout<<"before sort: "<
cout<
std::sort(s.begin(), s.end());
cout<<"sort default: "<
cout<
//////////////////////////////////////////////////////////////////////////
cout<<"========== sort std::vector ==============="<
std::vector v2;
v2.push_back(Vec2D(3.f, -1.f));
v2.push_back(Vec2D(1.f, 6.f));
v2.push_back(Vec2D(3.f, 3.2f));
v2.push_back(Vec2D(2.f, 0.f));
cout<<"before sort: "<
print_vector(v2);
// 使用自定义排序算法
std::sort(v2.begin(), v2.end(), sort_comp_Vec2D);
cout<<"sort user defined: "<
print_vector(v2);
//////////////////////////////////////////////////////////////////////////
cout<<"========== sort std::vector ==============="<
std::vector v3;
v3.push_back(Vec3D(1.f, 0.f, 0.f));
v3.push_back(Vec3D(1.f, 1.f, 1.f));
v3.push_back(Vec3D(0.f, 2.f, 0.f));
v3.push_back(Vec3D(0.f, 1.f, 1.f));