编译时std :: vector的大小[重复]

问题描述 投票:-1回答:4
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
4个回答
5
投票
constexpr std :: vector目前不支持(2020年5月)。它计划于C ++ 2020。

这里是proposal p1004r2

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

Status in GCC

prototype implementation in LLVM


1
投票
[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);


0
投票

我看起来像这样,但是您将很难适应该表达式中比int更复杂的结构

#include <initializer_list> #include <iostream> #include <vector> typedef struct MYSTRUCT { int a; int b; } MYSTRUCT; int main() { constexpr auto myInitializer = std::initializer_list< MYSTRUCT >({{1,1} ,{2,2}, {3,3}}) ; constexpr size_t size = myInitializer.size(); std::vector<MYSTRUCT> my_vector(myInitializer); std::cout << "Vector size: " << my_vector.size() << " from constexpr " << size << std::endl; }


-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); //for the array size (memory that ocuppies) std::cout<<sizeof(array)/sizeof(array[0]); //for array elements return 0; }
© www.soinside.com 2019 - 2024. All rights reserved.