QT容器类问题
QT container class issue
我试图创建一个函数,该函数返回最初存储在QList<company*> list
中的公司的QStringList
。当我尝试向QStringList
添加项目时,我得到以下错误:
C:QtQt5.3.0ToolsQtCreatorbintestcompanylist.cpp:13: error: passing 'const QStringList' as 'this' argument of 'QList<T>& QList<T>::operator+=(const T&) [with T = QString]' discards qualifiers [-fpermissive]
m_sortedList += m_companyList.at(i)->toString();
^
知道我做错了什么吗?我也试过使用m_sortedList.append()
没有运气…
QStringList CompanyList::getCompanyList() const {
for (int i = 0; i <= m_companyList.length(); ++i) {
m_sortedList += m_companyList.at(i)->toString();
}
m_sortedList.sort();
return m_sortedList;
}
在getCompanyList() const
中,所有成员都是const。因此,m_sortedList
的类型是const QStringList
,您不能修改它。
没有理由将m_sortedList
作为成员,因为您总是覆盖它。而且,你似乎从来不打扫它。如果多次调用(非const) getCompanyList
,将得到一个包含重复项的列表。
为了避免在增加一个已知大小的列表时过早悲观化,您应该通过调用reserve
来确保它有足够的元素空间。
您正在寻找的是典型的局部返回值习惯用法:
// C++11
QStringList CompanyList::getCompanyList() const {
QStringList result;
result.reserve(m_companyList.size());
for (auto c : m_companyList) result << c->toString();
std::sort(result.begin(), result.end());
return result;
}
// C++03, this is a more declarative style loved by some OSS projects :)
QStringList CompanyList::getCompanyList() const {
QStringList result;
result.reserve(m_companyList.size());
std::transform(c.begin(), c.end(), std::back_inserter(result),
std::mem_fn(&company::toString));
std::sort(result.begin(), result.end());
return result;
}
// C++98
QStringList CompanyList::getCompanyList() const {
QStringList result;
result.reserve(m_companyList.size());
foreach (company * c, m_companyList) result << c->toString(); // or Q_FOREACH
std::sort(result.begin(), result.end());
return result;
}
相关文章:
- 如何正确实现容器类中元素的更改?
- C++ 用于检查容器类中是否存在函数和隐式推导规则的概念
- 容器类中的类迭代器
- 返回持有 std::mutex 锁的 RAII 容器类
- C++ 如何在容器类复制构造函数中复制分配器对象
- 如何使用迭代器设计模式为 C++ 中的包装容器类提供多个迭代器?
- 如何在模板容器类中实现复制构造函数和赋值运算符
- 问题:在类中创建动态数组
- 在容器类中使用带有共享_ptr/unique_ptr的虚拟对象
- 在自定义容器类上反转基于范围的 for 循环
- C++ 在容器类中使用自定义比较器的排序集
- 在类组合中,使包含的类可以访问容器类变量
- 为什么 std::to_string 不支持容器类作为输入?
- 从可变参数模板容器类中调用给定可变参数的 in 和 out 方法
- 是否有不变的STL容器类
- 什么是C++中的容器类,任何人都可以举个好例子
- 支持自定义 const 本机C++容器类的"for each"
- 容器类 c++ 的循环
- C 访问容器类方法
- QT容器类问题