简体   繁体   中英

Static 2d array

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?

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] {

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.

It depends on your compiler, but most of the times a double array's name counts as a double pointer. So in your case twitterCounts is a float**.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM