データの整列
Posted feedbacks - C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | #include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <cmath>
struct Pos
{
double x;
double y;
Pos() : x(0), y(0) {}
Pos(double x, double y) : x(x), y(y) {}
double length() const { return std::sqrt(x*x + y*y); }
};
bool lexicalOrder(const Pos& lhs, const Pos& rhs)
{
return (lhs.x < rhs.x) ||((lhs.x == rhs.x) && (lhs.y < rhs.y));
}
bool lengthOrder(const Pos& lhs, const Pos& rhs)
{
return lhs.length() < rhs.length();
}
std::ostream& operator << (std::ostream& out, const Pos& pos)
{
return out << '(' << pos.x <<',' << pos.y << ')';
}
int main(int, char* [])
{
std::vector<Pos> a;
a.push_back(Pos(1, 1));
a.push_back(Pos(3, 3));
a.push_back(Pos(0, 0));
a.push_back(Pos(0, 3));
a.push_back(Pos(4, 0));
std::sort(a.begin(), a.end(), lexicalOrder);
std::copy(a.begin(), a.end(), std::ostream_iterator<Pos>(std::cout, " "));
std::cout << "\n";
// (0,0) (0,3) (1,1) (3,3) (4,0)
std::sort(a.begin(), a.end(), lengthOrder);
std::copy(a.begin(), a.end(), std::ostream_iterator<Pos>(std::cout, " "));
std::cout << "\n";
// (0,0) (1,1) (0,3) (4,0) (3,3)
return 0;
}
|
座標の値が不変なら、長さをキャッシュして毎回計算しないようにしますよね。(蛇足か...)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | % diff -u 5866.cpp.orig 5866.cpp
--- 5866.cpp.orig 2008-02-27 19:06:45.000000000 +0900
+++ 5866.cpp 2008-02-27 19:10:30.000000000 +0900
@@ -8,9 +8,8 @@
{
double x;
double y;
- Pos() : x(0), y(0) {}
- Pos(double x, double y) : x(x), y(y) {}
- double length() const { return std::sqrt(x*x + y*y); }
+ double length;
+ Pos(double x, double y) : x(x), y(y), length(std::sqrt(x*x + y*y)) {}
};
bool lexicalOrder(const Pos& lhs, const Pos& rhs)
@@ -20,7 +19,7 @@
bool lengthOrder(const Pos& lhs, const Pos& rhs)
{
- return lhs.length() < rhs.length();
+ return lhs.length < rhs.length;
}
|




odz #5839() Rating1/1=1.00
(x, y) の座標情報を以下の2種類の方法で整列する機能を実現してください。
データの表現方法はタプルなり構造体/オブジェクトなり各自で適当に選んで下さい。
[ reply ]