编译时的向量元素计数

问题描述 投票:-1回答:3

Visual Studio 2019,C ++ 17

如何在编译时确定myVector(MYSIZE)中的元素数量?

typedef struct
{
    char text[64];
    int a;
    int b;
} MYSTRUCT;

const std::vector <MYSTRUCT> myVector
{
    {"abc", 0, 0},
    {"defgh", 0, 0},
    {"ij", 0, 0}
}   
constexpr MYSIZE = ?

int main()
{
    int arr[MYSIZE] = { 0 };

    ...
    ...
}
c++ sizeof constexpr
3个回答
2
投票

constexpr std :: vector目前不支持(2020年5月)。它计划于C ++ 2020。

这里是proposal p1004r2

这里是compatibility matrix(可悲的是,任何编译器均不支持P1004R2):

Status in GCC

prototype implementation in LLVM


0
投票

[std::vector]尚不能用于编译时表达式,即使在C ++ 20中,也不能具有constexpr std::vector

或者,您可以使用std::array

constexpr std::array myVector
{
    MYSTRUCT{"abc", 0, 0},
    MYSTRUCT{"defgh", 0, 0},
    MYSTRUCT{"ij", 0, 0}
};
constexpr std::size_t MYSIZE = myVector.size();

或C数组:

constexpr MYSTRUCT myVector[] =
{
    {"abc", 0, 0},
    {"defgh", 0, 0},
    {"ij", 0, 0}
};
constexpr std::size_t MYSIZE = std::size(myVector);

-1
投票
typedef struct
{
    char text[64];
    int a;
    int b;
} MYSTRUCT;

const MYSTRUCT array[]={
    {"abc", 0, 0},
    {"defgh", 0, 0},
    {"ij", 0, 0}
};

int main()
{
    std::cout<<sizeof(array);
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.