私は入門的なC++クラスであり、.ppmの画像ファイルを読み込んでコピーした後、出力ファイルに書き込むプログラムを書くことが任されています。クラスのベクトルのベクトル内の値にアクセスする方法
私のPpmPictureクラスにはベクトルのベクトルがあり、各インデックスには赤、緑、青のintを持つPixelが含まれています。
私の問題は出力関数で、私はそれらのintをファイルに出力しようとしています。個別にアクセスするにはどうすればよいですか?ここで私のコードは、私は私のwritePpmFile関数の下部にこれらの値を出力しようとしているのを見ることができます。私はpicture.red [0] [0]が意味を成さないことを知っています、私はただの解決策を強制しようとしていました、そして、私が最後にやったことが起こったのです。
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;
struct Pixel {
Pixel();
Pixel(int redValue, int greenValue, int blueValue);
int red;
int green;
int blue;
};
Pixel::Pixel() {
red = 0;
green = 0;
blue = 0;
}
Pixel::Pixel(int redValue, int greenValue, int blueValue) {
red = redValue;
green = greenValue;
blue = blueValue;
}
class PpmPicture {
public:
PpmPicture();
bool readPpmFile(string inputFile);
int writePpmFile(string outputFile);
private:
vector<vector<Pixel> > picture;
int rows;
int columns;
int intensity;
};
PpmPicture::PpmPicture() {
rows = 0;
columns = 0;
}
int main(int argc, char *argv[]) {
PpmPicture myPic;
if(argc != 3) {
cout << "usage: inputfile outputfile";
return 0;
}
myPic.readPpmFile(argv[1]);
myPic.writePpmFile(argv[2]);
}
bool PpmPicture::readPpmFile(string inputFile) {
Pixel pix;
vector<Pixel> tempArray;
fstream fin;
string fileType;
int i, j;
fin.open(inputFile.c_str());
//Check if file opened
if(fin.fail()) {
return false;
}
while(!fin.eof()) {
//Input first four values into appropriate variables
fin >> fileType >> columns >> rows >> intensity;
//Fill tempArray with pixel values
while(fin >> pix.red >> pix.green >> pix.blue) {
tempArray.push_back(pix);
}
}
//Read file until you reach the number of rows specified by the file
for(j = 0; j < rows; j++) {
//Input pixel values into each index in the row array
//Enter new row when one row's width is achieved
for(i = 0; i < columns; i++) {
picture[j].push_back(tempArray[i]);
}
}
return true;
}
int PpmPicture::writePpmFile(string outputFile) {
ofstream fout;
int i, j, temp;
fout.open(outputFile.c_str());
if(fout.fail()) {
return -2;
}
if(columns < 0 || rows < 0) {
return -1;
}
fout << "P3" << endl;
fout << columns << rows << endl;
fout << intensity << endl;
fout << picture.red[0][0];
fout << picture.green[0][0];
fout << picture.blue[0][0];
/*for(j = 0; j < rows; j++) {
for(i = 0; i < columns; i++) {
fout << picture[j][i] << " ";
}
}*/
return 0;
}
私は、これは私たちがショートカット/さまざまな機能の多くを介して行っていない入門クラスで言ったように私は、追加する必要があります。だから可能ならそれをいくらかシンプルに保つこと(それが効率的でなくても)が望ましいでしょう:)
としてinstを考えますPpmPictureのインスタンス: inst.picture.at(i).at(k) –
'picture [j] [i]'は、[i] [j]の位置の 'pixel'を返します。通常のピクセルインスタンスのr、g、b値はどうやって取得できますか? – NathanOliver
もちろんPixelインスタンスを返します。@ NathanOliverが示すようにRGBの値を取得するメソッドを実装する必要があります –