PDA

View Full Version : Trouble with QMap



bikonja
12th June 2015, 17:09
Hello, i got a question.

Consider the following code

parser.h


class parser : public QObject

{
Q_OBJECT
public:
explicit parser(QObject *parent = 0);

void process_line(QString line, QMap<QString,double> my_map);
int read_line(QMap<QString,double> my_map);
void print_map(QMap<QString,double> my_map);

};

parser.cpp



void parser::process_line(QString line, QMap<QString, double> my_map)
{
QStringList temporary_list;

for(int i = 0; i< currency_list.size();i++)
{
if(line.contains(currency_list.at(i),Qt::CaseInsen sitive))
{
qDebug()<<"found"<< currency_list.at(i);
temporary_list=line.split(" ",QString::SkipEmptyParts);
qDebug()<< temporary_list[6];
temporary_list.replaceInStrings(",",".");
my_map.insert(currency_list.at(i),temporary_list[6].toDouble());
}
}

}

int parser::read_line(QMap<QString, double> my_map)
{

QFile file("C:/Qt/test/downloaded.txt");

if(!file.exists())
{
QMessageBox msgBox;
msgBox.setText("There is no such file");
msgBox.exec();
return 1;
}

if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
QMessageBox msgBox;
msgBox.setText("Error while opening file");
msgBox.exec();
return 1;
}

QTextStream in_stream(&file);
QString line=in_stream.readLine();


while (!line.isNull())
{
process_line(line, my_map);
line = in_stream.readLine();
}


return 0;
}

void parser::print_map(QMap<QString, double> my_map)
{
QMapIterator<QString, int> i(map);
while (i.hasNext()) {
i.next();
qDebug()<< i.key() << ": " << i.value() << endl;
}

i tried this to test for data.


void parser::print_map(QMap<QString, double> my_map)
{
QMapIterator<QString, int> i(map);
if(!i.hasNext()) {
qDebug()<< "nothing here" << endl;
}

and it shows that nothing is there

and in my main

main.cpp


int main(int argc, char *argv[])
{
QApplication a(argc, argv);

QMap<QString,double> currency_map;

MainWindow w;
w.show();

parser p;
p.read_line(currency_map);

p.print_map(currency_map);

return a.exec();
}


What am i doing wrong while trying to print (and maybe even saving) keys/values in my map?
my read_line() works ok, qdebugger is showing everything and im also under the impression that my process_line works ok as well.

I need to use the map in other classes as well, so im thinking it would be most painless to make it in my main and send it around.
But im obviously missing something here, would appreciate it if you could help me out.

Thx

ChrisW67
12th June 2015, 20:41
You are passing a copy of the map into read_line() And process_line(). Each function modifies its own copy and then the copy is discarded at the end of the function. Pass the map by non-const reference if you want to modify the passed map.