C++ QMap值作为结构
假设我们有这个样本:C++ QMap值作为结构,c++,qt,qmap,C++,Qt,Qmap,假设我们有这个样本: struct test { QString name; int count = 0; }; QMap<QString,test> map; test test1; test1.name = "doc1"; map.insertMulti("pen",test1); test test2; test2.name = "doc2"; map.insertMulti("pen",test2); if(map.contains("pen")) {
struct test
{
QString name;
int count = 0;
};
QMap<QString,test> map;
test test1;
test1.name = "doc1";
map.insertMulti("pen",test1);
test test2;
test2.name = "doc2";
map.insertMulti("pen",test2);
if(map.contains("pen"))
{
map.value("pen",test1).count++; // Here goes the error
//map["pen"].count++; //works but increments count of last inserted struct
}
foreach (test value, map) {
qDebug() << value.name << " " << value.count;
}
所以我要做的是检查键是否已经存在,然后增加我需要的结构的计数
请建议如何正确执行此操作。返回一个无法修改的常量值,您必须使用迭代器,方法如下:
更新:
对于QMap,必须使用返回存储值引用的:
struct Test{
QString name;
int count = 0;
};
QMap<QString, Test> map;
Test test1;
test1.name = "doc1";
map.insertMulti("pen",test1);
Test test2;
test2.name = "doc2";
map.insertMulti("pen", test2);
if(map.contains("pen")){
qDebug() << "before: " << map.value("pen").count;
map["pen"].count++;
qDebug() << "after: " << map.value("pen").count;
}
更新:
您必须使用来获取具有键的第一个元素的迭代器,如果您想要访问具有相同键的元素,则必须增加迭代器
struct Test{
QString name;
int count = 0;
};
QMap<QString, Test> map;
Test test1;
test1.name = "doc1";
map.insertMulti("pen",test1);
Test test2;
test2.name = "doc2";
map.insertMulti("pen", test2);
if(map.contains("pen")){
// get the first item with the key
QMap<QString, Test>::iterator it = map.find("pen");
// the next element
it++;
// update value
it->count++;
}
for(const Test & value: map){
qDebug() << value.name << " " << value.count;
}
抱歉,在你发布答案之前,我编辑了我的问题。请检查新修改的一个,我理解,但我的问题是,我需要增加特定结构的计数,例如test1。您的结果增加了test2的计数。欢迎使用堆栈溢出!请拿着这本书读一读。关于你的问题,你应该在这里提问之前提取a,具体来说,如果没有实际的错误,错误是毫无价值的。
struct Test{
QString name;
int count = 0;
};
QMap<QString, Test> map;
Test test1;
test1.name = "doc1";
map.insertMulti("pen",test1);
Test test2;
test2.name = "doc2";
map.insertMulti("pen", test2);
if(map.contains("pen")){
qDebug() << "before: " << map.value("pen").count;
map["pen"].count++;
qDebug() << "after: " << map.value("pen").count;
}
before: 0
after: 1
struct Test{
QString name;
int count = 0;
};
QMap<QString, Test> map;
Test test1;
test1.name = "doc1";
map.insertMulti("pen",test1);
Test test2;
test2.name = "doc2";
map.insertMulti("pen", test2);
if(map.contains("pen")){
// get the first item with the key
QMap<QString, Test>::iterator it = map.find("pen");
// the next element
it++;
// update value
it->count++;
}
for(const Test & value: map){
qDebug() << value.name << " " << value.count;
}
"doc2" 0
"doc1" 1