転置行列

#geshi(cpp){{

#include <iostream>

#include <vector>

#include <string>

int main(){

	std::vector< std::vector<double> > matrix;
	std::vector<double> row;
	char tmp;
	std::string str("");
	while(std::cin.get(tmp)){
		switch(tmp){
			case ' ':
				if(str != "")
					row.push_back(atof(str.c_str()));
				str="";
				break;
			case '\n':
				if(str != "")
					row.push_back(atof(str.c_str()));
				matrix.push_back(row);
				row.clear();
				str="";
				break;
			default:
				str += tmp;
				break;
		}
	}
	if(str != "")
		row.push_back(atof(str.c_str()));
	if(row.size() != 0)
		matrix.push_back(row);
	for(unsigned int j=0; j < matrix[0].size(); j++){
		for(unsigned int i=0; i < matrix.size(); i++){
			std::cout << matrix[i][j] << ' ';
		}
		std::cout << std::endl;
	}
	return 0;

} }}

vector (begin, end)を使って

#geshi(cpp){{

#include <sstream>

#include <iostream>

#include <vector>

#include <string>

#include <iterator>

int main(){

	std::vector< std::vector<double> > matrix;
	std::string str;
	while(getline(std::cin, str)){
		std::istringstream iss(str);
		std::vector<double> row( (std::istream_iterator<double>(iss)),
			std::istream_iterator<double>() );
		matrix.push_back(row);
	}
	for(unsigned int j=0; j < matrix[0].size(); j++){
		for(unsigned int i=0; i < matrix.size(); i++){
			std::cout << matrix[i][j] << ' ';
		}
		std::cout << std::endl;
	}
	return 0;

} }} aaaa


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS