[英]Use push_back() to add an item in a vector, the size of the vector increase but can't read values from the vector
I have a class ColorName, and a class ColorNameLookup. 我有一个类ColorName和一个类ColorNameLookup。 In class ColorNameLookup, there is a public member: vector colorList.
在ColorNameLookup类中,有一个公共成员:矢量colorList。 And the constructor of class ColorNameLookup is to add items into the vector colorList.
ColorNameLookup类的构造函数是将项目添加到向量colorList中。
I add 140 items into the vector colorList. 我将140个项目添加到向量colorList中。 I checked the size of the vector is correct, but I can't read any value from the vector.
我检查了向量的大小是否正确,但是我无法从向量中读取任何值。
For instance, I initialize a variable ColorNameLookup findColor
, and use function findColor.colorList[0].getR()
to get the first element's R value. 例如,我初始化变量
ColorNameLookup findColor
,并使用函数findColor.colorList[0].getR()
获取第一个元素的R值。 The return is an uninitialized integer value. 返回值是未初始化的整数值。
my code is shown below: 我的代码如下所示:
Class ColorName: 类ColorName:
#include "ColorName.h"
ColorName::ColorName(std::string name, int r, int g, int b)
{
r = r;
g = g;
b = b;
name = name;
}
ColorName::ColorName(void)
{
}
ColorName::~ColorName(void)
{
}
int ColorName::computeMSE(int pixR, int pixG, int pixB) {
return ((pixR-r)*(pixR-r) + (pixG-g)*(pixG-g) + (pixB-b)*(pixB-b)/3);
}
int ColorName::getR() {
return r;
}
int ColorName::getG() {
return g;
}
int ColorName::getB() {
return b;
}
std::string ColorName::getName() {
return name;
}
Class ColorNameLookup: 类ColorNameLookup:
ColorNameLookup::ColorNameLookup(void)
{
colorList.push_back(ColorName("AliceBlue",0xF0,0xF8,0xFF));
//...139 push_back
colorList.push_back(ColorName("YellowGreen",0x9A,0xCD,0x32));
}
ColorNameLookup::~ColorNameLookup(void)
{
}
std::string ColorNameLookup::getColorName(int r, int g, int b) {
ColorName closestMatch; // = NULL;
int findFlag = 0;
int minMSE = std::numeric_limits<int>::max();
int mse;
for (ColorName c : colorList) {
mse = c.computeMSE(r, g, b);
if (mse < minMSE) {
findFlag = 1;
minMSE = mse;
closestMatch = c;
//printf("Find color!\n");
}
}
if (findFlag ==1){
return closestMatch.getName();
}
else
return NULL;
}
You'd need this: 您需要这个:
ColorName::ColorName(std::string name, int r, int g, int b)
{
this->r = r;
this->g = g;
this->b = b;
this->name = name;
}
r = r
would just assign the same local r
to itself, and leave the member variables uninitialized. r = r
只会为其自身分配相同的局部r
,而成员变量未初始化。
For initializing these members, you'd be better off with an initializer list though: 为了初始化这些成员,最好使用一个初始化列表:
ColorName::ColorName(std::string name, int r, int g, int b) :
r(r),
g(g),
b(b),
name(name)
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.