View Full Version : How to modify qmap without iteration
sanjarbek
11th April 2010, 12:24
How to modify QMap without iteration,
In my code I verify qmap if it has a key.
If no then I insert a new key and value. If yes then I want to increment a value.
How to do this?
Sorry for my English.
spud
11th April 2010, 15:10
if(!map.contains(key))
map.insert(key, defaultValue);
else
map[key]++;
sanjarbek
12th April 2010, 14:18
if(!map.contains(key))
map.insert(key, defaultValue);
else
map[key]++;
yes, it works, but I tried this
QMap<QString, int > *temp = new QMap<QString, int >;
temp->insert("first", 1);
temp["first"] = 2;
and get this error
C:/QtProjects/NaiveBayesian/attribute.cpp:42: error: invalid types 'QMap<QString, int>*[const char [6]]' for array subscript
spud
12th April 2010, 16:25
This is an ugly C++ pitfall. Since temp is a pointer, you would have to write:
(*temp)["first"] = 2;
but an altogether better approach would be:
QMap<QString, int > temp;
temp.insert("first", 1);
temp["first"] = 2;
See implicit sharing (http://doc.trolltech.com/latest/shared.html).
sanjarbek
12th April 2010, 17:17
Thank you, it is working, but it seems some ugly.
I need to create QMap variable dynamically.
spud
12th April 2010, 17:20
I need to create QMap variable dynamically.
Dynamically, sure. On the heap, probably not.
Have you read about implicit sharing?
sanjarbek
12th April 2010, 17:33
Dynamically, sure. On the heap, probably not.
Have you read about implicit sharing?
Yes, I have read it before.
In my program I have a class which have 3 members: bool, QMap, int.
In the case of bool variable I need either QMap or int.
This is why I want to create variables dynamically.
sanjarbek
12th April 2010, 18:14
I changed my code.
QMultiMap<QString, QMap<QString, int> > mTable;
if (mTable.value(instancevalue).contains(classname))
mTable[instancevalue][classname]++;
else
mTable[instancevalue].insert(classname, 1);
get this error message
C:/QtProjects/NaiveBayesian/../../Qt/2010.02.1/qt/include/QtCore/../../src/corelib/tools/qmap.h:1013: error: 'T& QMultiMap<Key, T>::operator[](const Key&) [with Key = QString, T = QMap<QString, int>]' is private
spud
12th April 2010, 20:51
See the documentation of QMultiMap:
Unlike QMap, QMultiMap provides no operator[]. Use value() or replace() if you want to access the most recently inserted item with a certain key
sanjarbek
13th April 2010, 10:07
I understood. Thank you for your help. Until now I used dotnet and now I pass to qt. My C++ background is good, just I get accustomed dotnet style model.
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.