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.
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