tags:

views:

63

answers:

2

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());
}
+3  A: 

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));
Mike Seymour
Yes, Qt's container are STL-compatible, so all the functional-style things you can do with STL containers you can do with Qt containers as well.Also have a look at boost::bind(). The overall syntax regarding STL plus functional programming might cause nausea for ruby or python hackers though ;)
Frank
A: 

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())); 
MSalters