c++ - 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"))
{
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;
}
所以我要做的是检查 key 是否已经存在,然后增加我需要的结构的计数。
请告知如何正确执行此操作。
解决方案
value()
返回一个无法修改的常量值,而不是您必须使用迭代器使用以下find()
方法:
struct Test{
QString name;
int count = 0;
};
QMultiMap<QString, Test> map;
Test test;
test.name = "doc1";
map.insert("pen", test);
if(map.contains("pen")){
qDebug() << "before: " << map.value("pen").count;
QMultiMap<QString, Test>::iterator it = map.find("pen");
it->count += 10;
qDebug() << "after: " << map.value("pen").count;
}
输出:
before: 0
after: 10
更新:
在 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;
}
输出:
before: 0
after: 1
更新:
您必须使用find()来获取具有键的第一个元素的迭代器,如果要使用相同的键访问元素,则必须增加迭代器。
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
推荐阅读
- mysql - Mysql 8 聚合
- ssis - 派生列转换长度错误:
- angular - Angular 响应式表单和 ControlValueAccessor,表单值始终为空
- django-templates - 为什么 django 在特定路径中找不到 img?
- reactjs - 无法在 AWS amplify 上部署 Next Js SSR 应用程序。(网站内部错误,cli 部署失败)
- html - 这样对齐两个p标签
- loops - 使用数据结构和循环进行迭代
- ruby-on-rails - Ruby on Rails:验证卡片的月份和年份
- typescript - 如何使无法访问的代码警告在 VSCode 中显示为错误?
- node.js - Node.js - 在终端中显示 ESLint 错误,如 create-react-app