Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static 2d array

Tags:

c++

arrays

static

I am trying to define and use a 2-d array in C++

const float twitterCounts[][5] = {
        {1,0,0,0,0},
        {0,2,0,0,0},
        {0,0,3,0,0}
};

returning it like this:

const float ??? TwitterLiveData::data() {
    return twitterCounts;
}

and using it like this

float x = TwitterLiveData::data()[1][1];

What is the proper signature for the static accessor?

like image 229
user1356937 Avatar asked Feb 20 '23 17:02

user1356937


2 Answers

You cannot return an array, but you can return the pointer to its first element or reference to the array. You just have to put the correct type in the signature:

const float (*TwitterLiveData::data())[5] {

Or maybe

const float (&TwitterLiveData::data())[3][5] {
like image 147
jpalecek Avatar answered Feb 28 '23 11:02

jpalecek


See: https://stackoverflow.com/a/10264383/365496

summary:

#include <array>

const std::array<std::array<float,5>,3>
twitterCounts = {
        {1,0,0,0,0},
        {0,2,0,0,0},
        {0,0,3,0,0}
};

const std::array<std::array<float,5>,3>
TwitterLiveData::data() {
    return twitterCounts;
}

You may not want to return the array by value as that could potentially be too expensive. You could return a reference to the array instead:

const std::array<std::array<float,5>,3> &TwitterLiveData::data();

In either case your desired syntax float x = TwitterLiveData::data()[1][1]; works.

like image 39
bames53 Avatar answered Feb 28 '23 09:02

bames53