I am trying to create a multidimensional array in c++ where there's a string and an int involved. I tried int test[1][2] = {{"a", 1}, {"b", 2}, {"c", 3}}; but g++ gave me the following:
example.cpp: In function ‘int getServer(std::string)’:
error: too many initializers for ‘int [1][2]’
error: invalid conversion from ‘const char*’ to ‘int’ [-fpermissive]
I tried to use char test[1][2] as well for the initializer, but this didn't work.
Edit: This will become a rather large multidimensional array and it's needed so that I can get values and store based on a loop control variable which will vary in its length.
Use std::pair:
std::array<std::pair<std::string, int>, 3> test{{"a", 1}, {"b", 2}, {"c", 3}};
std::pair works with C++03, but the initialization and array type I used are C++11. You can still use a normal array and a bunch of std::make_pair calls.
Now you can access each inner element with an index and first or second:
test[0].first //"a"
test[2].second //3
This is not allowed in c++. An array can only have one type, so specifying an array with two types like that does not actually make sense.
My idea to do this would be to define a struct:
struct pair {
std::string s;
int i;
}
And then define a one dimensional array of type pair. Then access your elements like array[0].s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With