Olivier Grech Olivier Grech - 2 months ago 10
C++ Question

Issue when iterating through a vector of struct

I have the following struct :

struct LZ77Code {
uint8_t nIdx;
uint8_t nLength;
uint8_t nNextSymbol;
};


I'm trying to fill a vector of this struct.

std::vector<LZ77Code> vCode;
std::vector<LZ77Code>::iterator vCodeIt = vCode.begin();

while (something)
{
/*Here I calculate the value of idxx, length, and nextSymbol*/

/*Part where I suspect the issue is*/
vCodeIt->nIdx = idx;
vCodeIt->nLength = length;
vCodeIt->nNextSymbol = nextSymbol;
vCodeIt++;
/*------------------------------*/
}


When I run my code without this last part, it runs fine. But when I add this part, it crashes (program.exe has stopped working). Any idea where that come from?

Answer

Problem is, that in

std::vector<LZ77Code> vCode;
std::vector<LZ77Code>::iterator vCodeIt = vCode.begin();

vCode is empty and vCode.begin() is pointing past last element (i.e. begin() == end()).

If you want to fill the vector with data, you can use vector::push_back.

while (something)
{
    /*Here I calculate the value of idxx, length, and nextSymbol*/
    LZ77Code code;
    code.nIdxx = idxx;
    code.nLength = length;
    code.nNextSymbol = nextSymbol;

    vCode.push_back(code);
}
Comments