如何在编译时确定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 };
...
...
}
这里是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);
我看起来像这样,但是您将很难适应该表达式中比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;
}
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;
}