QT容器类问题

时间:2015-08-07 15:15:26

标签: c++ qt

我正在尝试创建一个函数,该函数返回最初存储在QStringList中的QList<company*> list个公司。当我尝试将项目添加到QStringList时,我收到以下错误:

C:\Qt\Qt5.3.0\Tools\QtCreator\bin\test\companylist.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;
}

1 个答案:

答案 0 :(得分:3)

getCompanyList() const内,所有成员都是const。因此,m_sortedList的类型为const QStringList,您无法对其进行修改。

但是,没有理由让m_sortedList成为会员,因为你总是会覆盖它。而且,你似乎永远不会清理它。如果您多次调用(非常量)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;
}
相关问题