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 };
...
...
}
constexpr std :: vector目前不支持(2020年5月)。它计划于C ++ 2020。
这里是compatibility matrix(可悲的是,任何编译器均不支持P1004R2):
[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);
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;
}