Internet man
Internet man

Reputation: 1155

Can I map lists in Qt?

This is already fairly concise, but it would be awesome if I could map the list a la Ruby. Say I have a QStringList myStringList which contains things like "12.3", "-213.0", "9.24". I want to simply map the whole thing using toDouble without having to iterate. Does Qt have a method for this?

// i.e. I would love a one-liner for the following
// NB QT provices foreach
QList<double> myDoubleList;
foreach(QString s, myStringList) {
    myDoubleList.append(s.toDouble());
}

Upvotes: 4

Views: 4170

Answers (2)

MSalters
MSalters

Reputation: 179819

A common solution is to wrap toDouble in a transform iterator. Roughly:

class TransformIterator : public std::iterator<input_iterator_tag, double, ptrdiff_t, double*, double&>
{
  StringList::const_iterator baseIter;
public:
  TransformIterator(StringList::const_iterator baseIter) : baseIter(baseIter) { }
  TransformIterator operator++() { ++baseIter; return *this; }
  double operator*() const { return baseIter->toDouble(); }
};

QList<double> myDoubleList(TransformIterator(myStringList.begin()),
                           TransformIterator(myStringList.end())); 

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254461

As far as I can tell, QT's containers have an interface compatible with the Standard containers, so you should be able to use Standard algorithms on them. In this case, something like

std::transform(myStringList.begin(), 
               myStringList.end(), 
               std::back_inserter(myDoubleList),
               std::mem_fun(&QString::toDouble));

Upvotes: 11

Related Questions