14

I tried copy content of one vector to a QVector using the following

std::copy(source.begin(), source.end(), dest.begin());

However the destination QVector still is empty.

Any suggestions ?

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Rajeshwar
  • 11,179
  • 26
  • 86
  • 158

4 Answers4

23

Look at:

std::vector<T> QVector::toStdVector () const

QVector<T> QVector::fromStdVector ( const std::vector<T> & vector ) [static]

From docs

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
trompa
  • 1,967
  • 1
  • 18
  • 26
8

'fromStdVector' has been explicitly marked deprecated recently. Use following code:

std::vector<...> stdVec;

// ...       

QVector<...> qVec = QVector<...>(stdVec.begin(), stdVec.end());
Sandro4912
  • 313
  • 1
  • 9
  • 29
Hadi Navapour
  • 241
  • 3
  • 5
  • 3
    I really don't see why QT team has deprecated this function. it seems quite useful and more easy to write in my mind ... – Kafka Oct 20 '20 at 13:46
5

If you are creating a new QVector with the contents of a std::vector you can use the following code as an example:

   std::vector<T> stdVec;
   QVector<T> qVec = QVector<T>::fromStdVector(stdVec);
NotJo
  • 63
  • 1
  • 8
dunc123
  • 2,595
  • 1
  • 11
  • 11
2

As the other answers mentioned, you should use the following method to convert a QVector to a std::vector:

std::vector<T> QVector::toStdVector() const

And the following static method to convert a std::vector to a QVector:

QVector<T> QVector::fromStdVector(const std::vector<T> & vector)

Here is an example of how to use QVector::fromStdVector (taken from here):

std::vector<double> stdvector;
stdvector.push_back(1.2);
stdvector.push_back(0.5);
stdvector.push_back(3.14);

QVector<double> vector = QVector<double>::fromStdVector(stdvector);

Don't forget to specify the type after the second QVector (it should be QVector<double>::fromStdVector(stdvector), not QVector::fromStdVector(stdvector)). Not doing so will give you an annoying compiler error.

Edwin Fernandez
  • 89
  • 1
  • 12
Donald Duck
  • 8,409
  • 22
  • 75
  • 99