Using QVector<> as std::vector<> without duplicating the data

  • Howdy!

    I'm working with a C++ library that takes a pointer to std::vector<double> and iterates over it, potentially reading millions of values. However, I also plot that data using QCustomPlot, which handles huge data sets quite nicely.

    The lib wants a std::vector<double>, QCustomPlot wants a QVector<double>. Is there a way to keep them both happy without duplicating the data into two vectors? The copy is fast, it just feels like a waste of memory.

  • Qt Champions 2017

    Nothing exist like that. If contents are address variable it would have saved something

  • Qt Champions 2017

    I assume you are using
    ( its still copy. just as in contrast to using a loop)

  • Lifetime Qt Champion


    fromStdVector copies the data.

    From a quick look at QCustomPlot (and really just a look), one solution that doesn't seem unreasonable is to modify the sources from QCustomPlot to use std::vector in place of QVector to handle your data.

  • Got it, thanks for these answers. Modifying one library or the other seems like a good solution.

  • Qt Champions 2017

    Well, there's also an alternative to modifying the QCustomPlot sources, but it comes with a disclaimer. Consider this specialization:

    class MyType; //< Whatever your type is
    template <>
    static inline QVector<MyType> QVector<MyType>::fromStdVector(const std::vector<MyType> & vector)
        QVector<MyType> tmp;
        tmp.d = QTypedArrayData<MyType>::fromRawData(, vector.size(), Unsharable);
        return tmp;

    Here goes the disclaimer:

    1. I haven't tested that, it's hacking into Qt's internals, so use at your own discretion.
    2. You have to ensure the std::vector instance will not go out of scope while any one QVector instance holds reference to the data

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.