Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ multidimensional array multiple data types

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.

like image 312
cellsheet Avatar asked Feb 22 '26 01:02

cellsheet


2 Answers

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
like image 147
chris Avatar answered Feb 23 '26 14:02

chris


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

like image 38
jmh Avatar answered Feb 23 '26 15:02

jmh