1

In my program I have an array "vector< vector<double> > convos" with 3 rows and an arbitrary number of columns Nconv. Each column represents a possible conversation between 2 individuals from a group with size N, and the 2nd & 3rd cells in each column contain a number labelling a particular individual.

So I've written a small section of code the cycle through this array and fill each column with a unique pair of integers eg.

convos[i][2] = 1 2 3 2 3

convos[i][1] = 0 0 0 1 1 .... and so on.

The code I've written for works, but is way too messy to leave out in the my int main(), and it's probably good practice to use external functions anyway.

My problem is that when I call the function insertpairs in my main code, nothing happens... Can anyone point out something obvious that I am missing here?

#include <iostream>
#include <vector>

using namespace std;
using std::vector;

void insertpairs(vector<vector<double> > convos, int Nconv, int N)
{
int a(0), b, c(0);
while (c < Nconv){
    b = a+1;
    while (b < N){
        convos[c][1] = a;
        convos[c][2] = b;
        b++;
        c++;
    }
   a++;
  }
 }

int main(){

int N(4), Nconv;
vector<vector<double> > convos;

Nconv = 0;
for (int i=1; i<=N; i++){
    Nconv = Nconv + N-i;
} // Calculates # of possible convos based on N.

insertpairs(convos, Nconv, N);
        // breakpoint here.
.....   // code continues, but rest isn't relevant.
}

If I put a breakpoint inside the void function I can see that it is working correctly, however when it finishes all the values in the array convos simply return to zero. Why is this?

fred
  • 23
  • 1
  • 5

1 Answers1

2

The vector doesn't change because you pass it by value:

void insertpairs(vector<vector<double> > convos, int Nconv, int N)

This means that the vector will be copied to a variable that is local to the function. The changes are done on that copy and it is destroyed after the function returns. You must pass the vector by reference:

void insertpairs(vector<vector<double> >& convos, int Nconv, int N)

See this question for more explanation of the difference.

Unless I'm mistaken, you pass an empty vector and add values to that? In that case, it might be simpler to not pass any vector but create a new one instead:

vector<vector<double> createpairs(int Nconv, int N) {
    vector<vector<double> pairs;
    // now add the pairs here
    return pairs;
}

And in main:

vector<vector<double> > convos = createpairs(Nconv, N);
Community
  • 1
  • 1
eerorika
  • 232,697
  • 12
  • 197
  • 326