J Xkcd
J Xkcd

Reputation: 423

How can use a vector name as a variable?

How would I use a vector function where the vector name is a variable? A rough sketch of what I'm referring to:

void someFunc(int x) {
    vector<int>v0;
    vector<int>v1;
    vector<int>v2;
    switch (x) {
    case 0: //var will be assigned v0
    case 1: //var will be assigned v1
    case 2: //var will be assigned v2
    }
    var.assign(10, 1); //eg. when x == 1, it will be v1.assign(10,1)
}

Upvotes: 3

Views: 412

Answers (2)

Jabberwocky
Jabberwocky

Reputation: 50778

Even simpler, you can use an array of vectors:

#include <vector>
#include <array>

using namespace std;

void someFunc(int x) {
  array<vector<int>, 3> v;    // 3 vectors here (0..2), but we could as well
                              // have 100 vectors.
  v[x].assign(10, 1);
}

Upvotes: 6

NathanOliver
NathanOliver

Reputation: 180414

The easiest way to do this is to use a pointer. In the switch statement you assign to the pointer the vector and then afterword you just access the assigned vector through that pointer. That would look like

void someFunc(int x) {
    vector<int> v0;
    vector<int> v1;
    vector<int> v2;
    vector<int>* var;
    switch (x) {
    case 0: var = &v0; break;
    case 1: var = &v1; break;
    case 2: var = &v2; break;
    }
    var->assign(10, 1); //eg. when x == 1, it will be v1.assign(10,1)
}

Upvotes: 6

Related Questions