c++ - QVector<int>[index] 返回另一个 QVector?

标签 c++ qt qvector

我是 C++ 编程的新手,所以我可能只是遗漏了一些东西,但我已经尝试解决这个问题将近一个小时了。

我有一套 QLabels在我的 UI我想每秒更新两次。它更新的数据存储在 QVector<int> 中尺寸为 12。

MainWindow::MainWindow(QWidget *parent) :
    [...]
    knobCoords(new QVector<int>(12)),
    updateTimer(new QTimer(this))
{
    connect(updateTimer, SIGNAL(timeout()), this, SLOT(updateCoordLabels()));
    updateTimer->start(500);
}

为了更新标签,我需要转换我的 int字符串的值。这是直接在 updateCoordLabels() 中完成的功能:

void MainWindow::updateCoordLabels() {
    tracker->updateCoordData(*knobCoords);
    ui->knobA_xCoordsLabel->setText(to_string(knobCoords[0]));
    ui->knobA_yCoordsLabel->setText(to_string(knobCoords[1]));
    ui->knobA_zCoordsLabel->setText(to_string(knobCoords[2]));
    ui->knobB_xCoordsLabel->setText(to_string(knobCoords[3]));
    [...]
    updateTimer->start(500);
}

但是,当我编译程序时,出现类型不匹配。出于某种原因,knobCoords[index]不返回 int正如预期的那样,但是一个 QVector<int>相反。

mainwindow.cpp:124: error: C2665: 'std::to_string': none of the 9 overloads could convert all the argument types
[...]
mainwindow.cpp:124: while trying to match the argument list '(QVector<int>)'

我做错了什么?

最佳答案

knobCoordsQVector<int>*这意味着你必须尊重 knobCoords在对其使用下标运算符之前。

你可以改为:

ui->knobA_xCoordsLabel->setText(to_string(knobCoords->at(0)));
ui->knobA_yCoordsLabel->setText(to_string(knobCoords->at(1)));
ui->knobA_zCoordsLabel->setText(to_string(knobCoords->at(2)));
ui->knobB_xCoordsLabel->setText(to_string(knobCoords->at(3)));

一些注意事项:

  1. 不要在不必要的情况下使用指针。除了您刚刚看到它们引入的困惑之外,如果在对象析构函数中没有正确处理它们,它们会导致内存泄漏。随着错误恢复的出现,一个更重要的问题
  2. 将您的业务逻辑与前端分开。朝着这个方向迈出的一个好步骤是从不在内部使用 Qt 容器。 Qt 在处理标准容器方面做得很好,而不是 QVector<int>。更喜欢vector<int>或者如果您使用的是修复尺寸:array<int, 12>
  3. Although it doesn't make any difference for QVector 对于标准容器,您要避免使用 at函数更喜欢下标运算符作为 at即使在发布时也会产生边界检查费用

关于c++ - QVector<int>[index] 返回另一个 QVector?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47942593/

相关文章:

c++ - CreateFile2、WriteFile 和 ReadFile : how can I enforce 16 byte alignment?

c++ - C++ 中的垃圾收集器

c++ - 在 fedora 20 上使 Qt 应用程序失败 :/usr/bin/ld: cannot find -lGL

qt - QML native `date` 类型如何更新?

c# - 如何将 C 数组映射到 C#?

c++ - 64 位 Linux c++ 通过管道在两个线程之间传递 STRUCT

qt - 缩放QGraphicsView时要调整QPen厚度吗?

c++ - 从 OpenMP 循环内部访问和编辑 aN ma 时出错

c++ - QDataStream读取到QVector

qt - QVectors 的 QHash