alabama_country @Wiki

C-assign-2009-01-09

最終更新:

alabama_country

- view
管理者のみ編集可

1月9日提出のソフトウェア演習課題

注意

余りに原始的だったので、かなり綺麗にしました。 これだけ綺麗になると気持ち悪いくらいですね。

ソース

#include <cmath>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
 
inline double SQUARE(int x)
{
	return (double)x * x;
}
 
class point
{
public:
	int x,y;
	friend std::ostream &operator<<(std::ostream &stream, point &obj);
};
 
std::ostream &operator<<(std::ostream &stream, point &obj)
{
	stream << '(' << obj.x << ',' << obj.y << ')';
	return stream;
}
 
class line
{
private:
	point from, to;
	double length;
public:
	void input(int x1, int y1, int x2, int y2);
	void calc_length(double &length);
	bool operator<(const line &a)const{
		return length < a.length;
	};
	friend std::ostream &operator<<(std::ostream &stream, line &obj);
	friend std::istream &operator>>(std::istream &stream, line &obj);
};
 
void line::input(int x1, int y1, int x2, int y2)
{
	from.x = x1;
	from.y = y1;
	to.x = x2;
	to.y = y2;
	calc_length(length);
}
void line::calc_length(double &length)
{
	length = sqrt(SQUARE(from.x - to.x) + SQUARE(from.y - to.y));
}
 
std::ostream &operator<<(std::ostream &stream, line &obj)
{
	stream << obj.from << ',' << obj.to << " : " << obj.length;
	return stream;
}
std::istream &operator>>(std::istream &stream, line &obj)
{
	int x1,y1,x2,y2;
	char c;
	if(!(stream >> x1 >> c >> y1 >> c >> x2 >> c >> y2))
		return stream;
	else if(c != ',')
		std::cerr << "Data form error." << std::endl;
	else
		obj.input(x1, y1, x2, y2);
	return stream;
}
 
class lines
{
private:
	std::vector<line> array_line;
public:
	void push(line &line){ array_line.push_back(line); };
	bool input(const char *filename);
	void sort();
	friend std::ostream &operator<<(std::ostream &stream, lines &obj);
	friend std::istream &operator>>(std::istream &stream, lines &obj);
};
 
bool lines::input(const char *filename)
{
	std::ifstream ifs(filename);
	if(!ifs.is_open())
	{
		std::cerr << "File Open Error." << std::endl;
		return false;
	}
 
	ifs >> *this;
	return true;
}
 
void lines::sort()
{
	std::sort(array_line.begin(), array_line.end());
}
 
std::ostream &operator<<(std::ostream &stream, lines &obj)
{
	for(std::vector<line>::iterator i = obj.array_line.begin();
		i != obj.array_line.end(); ++i)
	{
		stream << *i << std::endl;
	}
	return stream;
}
 
std::istream &operator>>(std::istream &stream, lines &obj)
{
	line temp_line;
	while((stream >> temp_line) && stream.good())
		obj.push(temp_line);
	return stream;
}
int main()
{
	lines data;
	if(!data.input("line-sjis.txt"))
		return 0;
 
	data.sort();
 
	std::cout << data;
	return 0;
}
記事メニュー
目安箱バナー