-4

I am new with C++, so sorry if the question is too simple. I am trying to append a double value to a double vector in iteration (fired by a timer). The function that is called in iteration is the following:

void cMain::update_vector(vector<double> vtr, double value) {
    vtr.push_back(value);
}

The callback of the timer is the following:

void cMain::on_serial_timer(wxTimerEvent& evt) {
    reading_buffer = serial_connection->readSerialPort(received_data, buffer_size);
    if (reading_buffer == buffer_size) {
        if (reading_file_flag) { write_to_file();};
        received_data_splitted = strtok(received_data, "\t\n");
        update_vector(time_vector, sample_count);
        update_vector(temperature_vector, atof(received_data_splitted));
        ++sample_count;
    };
    evt.Skip();
}

The declarations of important variables for the question are the following:

int sample_count = 1;
char received_data[255];
char* received_data_splitted;
void update_vector(vector<double> vtr, double value);
vector<double> time_vector = vector<double>(1,0);
vector<double> temperature_vector = vector<double>(1, 0);

My issue is, I would expect the vector to increase in size on each iteration with the new value that is being appended. Instead, only the last value is substituted on each iteration with the values I am passing to push_back().

I have checked this might be caused when passing the pointer to push_back(), instead of the value itself, however in debug mode on I have checked I am passing a double value to push_back():

Capture of debug mode variables inside the function

Second iteration

Any help would be appreciated. Thanks!

OMS
  • 57
  • 1
  • 9
  • 2
    Please refer to your [C++ Textbook](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)'s section on passing by value versus passing by reference – alter_igel Mar 08 '21 at 20:25

1 Answers1

4
void cMain::update_vector(vector<double> vtr, double value) {
    vtr.push_back(value);
}

This passes vtr by value (i.e. a copy is made passing it to the function), then you push a value onto this copy, and finally it goes out of scope which deletes the copy.

It looks like what you are trying to do is add a value to an existing container. In this case you should pass by reference. This will allow the function to modify the original vector:

void cMain::update_vector(vector<double> & vtr, double value) {
                                  //    ^^^

    // vtr now refers to the original value
    vtr.push_back(value);
    // so this push is done on the original value.
}
Martin York
  • 257,169
  • 86
  • 333
  • 562
ravenspoint
  • 19,093
  • 6
  • 57
  • 103