PDA

View Full Version : [SOLVED] QVector iterator seg fault using .begin/.end



pheonixstorm
9th January 2011, 04:39
Built an app (don't sue me apple!) very similar to the addressbook tutorial (used QVector not QMap) and having issues using a next and previous function. As far as I can tell when it gets to checking for it == .begin() and changin it = .end() the it crashes instead of going to the end of the vector.

mpledit.cpp
void MplEdit::previousCargo()
{
if (it == MPLVec.begin())
it = MPLVec.end();

if (it == MPLVec.end()) {
ui->fileEdit->clear();
ui->categoryEdit->clear();
ui->priceEdit->clear();
ui->massEdit->clear();
ui->volumeEdit->clear();
ui->descEdit->clear();
}

ui->fileEdit->setText(it->getFile());
ui->categoryEdit->setText(it->getCategory());
ui->priceEdit->setText(it->getPrice());
ui->massEdit->setText(it->getMass());
ui->volumeEdit->setText(it->getVolume());
ui->descEdit->setText(it->getDesc());

it--;
}
mpledit.h
QVector<MPL> MPLVec;
QVector<MPL>::iterator it;
QVector<MPL>::const_iterator sav;

When i mouseover MPLVec.begin() it tells me that begin is const_iterator QVector::begin const when I *think* it should be telling me iterator QVector::begin () instead. Don't know if thats the issue or not... the const iterator save is only used in the saveCargo function and has no issues. I have tried clean project, removing all references to const_iterator (and just used two QVector:: iterator calls) but so far no luck. If you need me to post additional code let me know.

Lykurg
9th January 2011, 08:15
the end() function is returning and iterater behind (= invalid) the vector. See inside the docs for "Container Classes" for a detailed explanation. So your app crashes since it is invalid. Dekrement the iterator and all should work fine.

pheonixstorm
9th January 2011, 08:43
Odd considering the same nearly the same code is in the addressbook tutorial
if (i == contacts.end()) {
nameLine->clear();
addressText->clear();
return;
}

if (i == contacts.begin())
i = contacts.end();

i--;

Ok, nevermind.. I found the issue. Its not a bad iterator but bad iterator placement in the code. After looking at the above code segment I noticed MY placement of it-- was after calling for the information to post in the line edits. So should have read
it--;
ui->something->settext(it->variable) instead of
ui->something->settext(it->variable)
it--;
Its always the stupid things you miss... Thanks for the info even though I didn't get a chance to read up on it before finding my blunder :o