C++ 退出函数后向量大小变为0
我觉得这是一个愚蠢的问题,但我很累,所以我想在这里问一下。我的向量大小是从2到0。首先,我调用流程:C++ 退出函数后向量大小变为0,c++,class,object,vector,scope,C++,Class,Object,Vector,Scope,我觉得这是一个愚蠢的问题,但我很累,所以我想在这里问一下。我的向量大小是从2到0。首先,我调用流程: void PPM::process(pmode_t pmode, const string &fname) { // read qcolors in fname read_qcolors(fname); // run proper process mode if (pmode == run_process1) process1(); else process2(); return;
void PPM::process(pmode_t pmode, const string &fname)
{
// read qcolors in fname
read_qcolors(fname);
// run proper process mode
if (pmode == run_process1) process1();
else process2();
return;
}
它调用read_qcolors(),创建大小为2的向量:
void PPM::read_qcolors(const string &fname)
{
// open fname: check status
//
// while (more data0 {
// read R G B values
// save to qcolors vector
// }
//
// close input file
ifstream filestream;
vector <RGB> qcolors;
string line;
stringstream ss;
unsigned int ui1, ui2, ui3;
cerr << "reading " << fname << '\n';
filestream.open(fname.c_str());
if (filestream.fail()) cerr << "qcolors file failed to open.\n";
while (getline(filestream, line)) {
if (filestream.eof()) break;
if (filestream.fail()) cerr << "error during reading of qcolors file.\n";
RGB rgb;
ss.str(line);
/* Apparently there are no formatting flags to tell
a stringstream to read a stream as uchars. So I store
the stream into insigned ints, then convert the unsigned
ints to unsigned chars when assigning the RGB values. */
ss >> ui1 >> ui2 >> ui3;
rgb.R = (unsigned char)ui1;
rgb.G = (unsigned char)ui2;
rgb.B = (unsigned char)ui3;
//empty stringstream
ss.str("");
//reset state flags
ss.clear();
qcolors.push_back(rgb);
}
filestream.close();
cerr << "qcolor size is " << qcolors.size() << '\n';
return;
}
void PPM::读取颜色(常量字符串和fname)
{
//打开fname:检查状态
//
//而(更多数据)0{
//读取R G B值
//保存到qcolors矢量
// }
//
//关闭输入文件
ifstream文件流;
矢量qcolors;
弦线;
细流ss;
无符号整数ui1、ui2、ui3;
cerr>ui3;
R=(无符号字符)ui1;
rgb.G=(无符号字符)ui2;
rgb.B=(无符号字符)ui3;
//空字符串流
ss.str(“”);
//重置状态标志
ss.clear();
qcolors.push_back(rgb);
}
filestream.close();
cerr您似乎在隐藏您的成员变量(在read_qcolors中):
矢量qcolors;
在这种情况下,只需删除此行,它将使用成员变量。您似乎在隐藏您的成员变量(在read\u qcolors中):
矢量qcolors;
在这种情况下,只需删除这一行,它将使用成员变量。请发布一个。我们需要查看代码。我们不能告诉基本信息,例如rgb_vector
是否是类的成员。发布一些代码dude:)请发布一个。我们需要查看代码。我们不知道基本的东西,比如rgb_vector
是否是这个类的成员。发布一些代码都德:)没问题,这是一个容易犯的错误。没问题,这是一个容易犯的错误。
void PPM::process1()
{
// for each pixel {
// find closest qcolor
// set pixel color to closest qcolor
// }
cerr << "img size: " << img.size() << '\n';
cerr << "qcolor size: " << qcolors.size() << '\n';
float distance, min_distance;
int min_index;
//go thru each element in the vector of the img pixels
for (int i=0; i<img.size(); i++) {
for (int j=0; i<qcolors.size(); j++) {
distance = img[i].distance(qcolors[j]);
cerr << "calced distance of " << distance << '\n';
if (distance < min_distance || j == 1) {
min_distance = distance;
min_index = j;
cerr << "set min distance to " << min_distance << '\n';
}
}
img[i] = qcolors[min_index];
}
return;
}