Macro: pass the content of a variable (example: int) as argument to a macro call

Hi,

I am trying to generate a couple of vectors, but the exact number of vectors that will be needed can only be determined at runtime. Therefore I had the idea to use a macro call and text substitution in order to declare the necessary number of vectors. Unfortunately, the arguments of a macro call are always (as far as I know) considered text only. So, the loop in my example below in which I am trying to generate the following code:
1
2
3
4
vector<int> vector0;
vector<int> vector1;
vector<int> vector2;
vector<int> vector3;

does not work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>
using namespace std;

#define declareVec(vecno) vector<int> vector##vecno;

int main()
{
    for (int i=0;i<4;i++){
       declareVec(i);
    }

    vector0.push_back(666);
    cout << "vector0[0]=" << vector0[0] << endl;

    return 0;
}


I get an an error message 'vector0' was not declared in this scope.

I also tried to initialize a string or char with the content "0" and then pass this string or char to the macro call, but this did not work either.

Is there any way in which I could use the content of an integer variable or any other variable as arguments for a macro call?
Or is there any other method to solve the problem?
Any hints are appreciated!
Last edited on
Macros are expanded before compilation so they know nothing about what happens at runtime. The compiler will see line 9-11 as
1
2
3
    for (int i=0;i<4;i++){
       vector<int> vectori;;
    }


To be able to have the number of vectors decided at runtime you can store the vectors in a vector.
1
2
3
4
5
6
7
8
9
int main()
{
	std::vector<std::vector<int>> v(4);

	v[0].push_back(666);
	cout << "v[0][0]=" << v[0][0] << endl;

	return 0;
}
Last edited on
Topic archived. No new replies allowed.