QT容器类问题

QT container class issue

本文关键字:问题 容器类 QT      更新时间:2023-10-16

我试图创建一个函数,该函数返回最初存储在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;
}