【问题标题】:copying a std::vector to a qvector将 std::vector 复制到 qvector
【发布时间】:2013-08-08 15:10:45
【问题描述】:

我尝试使用以下方法将一个向量的内容复制到QVector

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

但是目的地QVector 仍然是空的。

有什么建议吗?

【问题讨论】:

标签: c++ qt


【解决方案1】:

看看:

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

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

From docs

【讨论】:

  • 试过了。作为MyQvector.fromStdVector(MyStedVector);,qvector 仍然是空的
  • @Rajeshwar:因为它是静态方法,尝试:MyQvector = QVector::fromStdVector( MyStedVector );
【解决方案2】:

'fromStdVector' 最近已明确标记为已弃用。 使用以下代码:

std::vector<...> stdVec;

// ...       

QVector<...> qVec = QVector<...>(stdVec.begin(), stdVec.end());

【讨论】:

  • 我真的不明白为什么 QT 团队已经弃用了这个功能。在我的脑海中似乎非常有用且更容易写...
【解决方案3】:

如果您要使用std::vector 的内容创建一个新的QVector,您可以使用以下代码作为示例:

   std::vector<T> stdVec;
   QVector<T> qVec = QVector<T>::fromStdVector(stdVec);

【讨论】:

    【解决方案4】:

    正如提到的其他答案,您应该使用以下方法将QVector 转换为std::vector

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

    以及将std::vector 转换为QVector 的以下静态方法:

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

    这里是一个如何使用QVector::fromStdVector的例子(取自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);
    

    不要忘记在第二个QVector 之后指定类型(应该是QVector&lt;double&gt;::fromStdVector(stdvector),而不是QVector::fromStdVector(stdvector))。不这样做会给你一个恼人的编译器错误。

    【讨论】:

      猜你喜欢
      • 2011-05-19
      • 1970-01-01
      • 2014-01-11
      • 1970-01-01
      • 2011-11-21
      • 2018-07-24
      • 1970-01-01
      • 2012-01-06
      • 2011-02-23
      相关资源
      最近更新 更多