可以使用以下方式将 std::vector 封装成 QVector:
#include <QVector>
#include <vector>
template<typename T>
QVector<T> toQVector(const std::vector<T>& vec) {
QVector<T> qVec;
for (const auto& element : vec) {
qVec.append(element);
}
return qVec;
}
int main() {
std::vector<int> stdVec = {1, 2, 3, 4, 5};
QVector<int> qVec = toQVector(stdVec);
// 使用封装后的 QVector 进行操作
if (qVec.isEmpty()) {
qDebug() << "QVector is empty";
} else {
qDebug() << "QVector size:" << qVec.size();
while (!qVec.isEmpty()) {
int frontValue = qVec.front();
qDebug() << "Pop front value:" << frontValue;
qVec.pop_front();
}
qDebug() << "After popping all elements, QVector size:" << qVec.size();
qVec.push_back(10);
qVec.push_back(20);
qDebug() << "After pushing two elements, QVector size:" << qVec.size();
// 使用迭代器遍历 QVector
for (auto it = qVec.begin(); it != qVec.end(); ++it) {
qDebug() << *it;
}
// 清空 QVector
qVec.clear();
qDebug() << "After clearing, QVector size:" << qVec.size();
}
return 0;
}
在上述示例中,通过 toQVector 函数将 std::vector 转换为 QVector,然后使用封装后的 QVector 进行操作。可以使用 isEmpty 判断 QVector 是否为空,使用 pop_front 弹出前面的元素,使用 size 获取 QVector 的大小,使用 clear 清空 QVector,使用 push_back 添加元素,以及使用 begin() 和 end() 迭代器遍历 QVector。
希望对你有所帮助!
内容由零声教学AI助手提供,问题来源于学员提问




