简体   繁体   English

静态2d数组

[英]Static 2d array

I am trying to define and use a 2-d array in C++ 我试图在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 请参阅: 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]; 无论哪种情况,你想要的语法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**. 所以在你的情况下,twitterCounts是一个浮动**。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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