Reputation: 1715
I am trying to create a function that returns a QStringList
of companies which were originally stored in a QList<company*> list
. When I try to add items to the QStringList
, I get the following error:
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();
^
Any idea what i'm doing wrong? i've also tried to use m_sortedList.append()
with no luck...
My code:
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;
}
Upvotes: 0
Views: 58
Reputation: 98435
Within getCompanyList() const
, all members are const. Thus, the type of m_sortedList
is const QStringList
and you can't modify it.
There's no reason to have m_sortedList
as a member, though, since you always overwrite it. Moreover, you never seem to clean it. If you'd call a (non-const) getCompanyList
more than once, you'd get a list with duplicated entries.
To avoid a premature pessimization when growing a list that will have a known size, you should ensure that it has room for enough elements by calling reserve
.
What you're looking for is the typical local return value idiom:
// 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;
}
Upvotes: 3