Question

So I am trying to create a simple program that allows me to manipulate a vector using a random function, but I feel that I am forgetting something fairly important & fundamental please feel free to look at the code I have posted & let me know what the solution is. The error I receive is that myvec is "index out of range which only means that the pushback didn't work in the insert method that I created. Not sure why, I am still a novice.

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QVector>

QVector<QString> myvec;

void insert(QVector<QString> vec);

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::insert(QVector<QString> vec){
    vec.push_back("Hello World");
}

void MainWindow::on_pushButton_clicked()
{
    insert(myvec);
    ui->label->setText(myvec.at(0));
}
Was it helpful?

Solution

Your function

void MainWindow::insert(QVector<QString> vec){
    vec.push_back("Hello World");
}

takes the vector by value. This means that when it's called, the argument is copied for use in the function, and when you modify the value there, it's not reflected on the instance outside of the function call (because the modification was done on the copy).

You want to pass the vector by reference so it's not copied, and modifications are done on the object which still lives outside the function call. This is done by adding & in the signature:

void MainWindow::insert(QVector<QString> & vec){
    vec.push_back("Hello World");
}

Note that you can also pass by const reference, which is often done for efficiency reasons. That means only a reference is passed to the function, but it isn't allowed to modify the instance within the function body.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top