简体   繁体   中英

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. In class ColorNameLookup, there is a public member: vector colorList. And the constructor of class ColorNameLookup is to add items into the vector colorList.

I add 140 items into the vector 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. The return is an uninitialized integer value.

my code is shown below:

Class 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(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.

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)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM