[英]Static function to convert QList of different types to QString
I have a QList which contains string, int, double and date values. 我有一个包含字符串,整数,双精度和日期值的QList。 I want to convert the QList to a QString and return it within a QString returning function. 我想将QList转换为QString并在QString返回函数中将其返回。 Is there a static function I can use or what am I missing here? 我可以使用静态功能吗?或者我在这里缺少什么? My current code: 我当前的代码:
QString Product::toString()
{
QStringList listString;
QString outString;
for(int i =0; i < size(); i++)
{
listString << at(i)->toString();
}
outString = listString.join("\n");
return outString;
}
Notes: 笔记:
I am assuming Product::at(int)
is returning a Transaction
, given a previous question. 考虑到先前的问题,我假设Product::at(int)
返回一个Transaction
。
I am also assuming OP mean "built-in" when he or she wrote"static" 我还假设OP在写“静态”时的意思是“内置”
The for
can be removed using built-in functions. 该for
可以使用内置的功能被移除。 Some (many?) will find the new syntax less understandable, though. 有些人(很多?)会发现新语法难以理解。
QString Product::toString()
{
QStringList aggregate;
std::transform(m_transactions.begin(),
m_transactions.end(),
std::back_inserter(aggregate),
std::bind(std::mem_fn(&Transactions::toString), std::placeholders::_1));
// or : [](const Transaction& transaction){ return transaction.toString(); });
return aggregate.join("\n");
}
std::transform
will transform every m_transactions
elements using Transaction::toString()
, and place the results into aggregate
. std::transform
将改变每一m_transactions
使用要素Transaction::toString()
,并将结果放到aggregate
。
std::back_inserter
means "use QStringList::push_bask
to record the results". std::back_inserter
意思是“使用QStringList::push_bask
记录结果”。 If QStringList
had a resize(int)
like QVector
does, we could have used aggregate.begin()
instead. 如果QStringList
像QVector
一样具有resize(int)
,我们可以改用aggregate.begin()
。
The unary function is a bit tricky, as it needs to be converted into a unary function, which what std::bind
/ std::mem_fn
is doing. 一元函数有点棘手,因为需要将其转换为std::bind
/ std::mem_fn
正在执行的一元函数。 If you are using C++11, you can use a lambda instead. 如果您使用的是C ++ 11,则可以改用lambda。
Also from the previous question, @SingerOfTheFall's remark is valid: 同样从上一个问题开始,@ SingerOfTheFall的评论是有效的:
I also find it a little odd to save transactions inside of products. 我还发现将交易保存在产品内部有点奇怪。 A better design would be having a separate class that could store them. 更好的设计是使用一个单独的类来存储它们。
If you keep this design, Transaction Product::at(int)
and int Product::size()
should be renamed to make the link with Transaction
explicit, like getTransaction
and getNumberOfTransactions
. 如果保持这种设计,应重命名Transaction Product::at(int)
和int Product::size()
以使与Transaction
的链接明确,如getTransaction
和getNumberOfTransactions
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.