如果您直到运行时才知道数组的大小,则要使用的容器是std::vector<myStruct>
. 但是,要做到这一点,您需要在myStruct
.
您可以使用从值std::transform
构造myStruct
对象int
并填充std::vector
.
示范代码:
#include <vector>
#include <algorithm>
struct myStruct
{
int value;
myStruct() : myStruct(0) {}
myStruct(int input)
{
value = input*input;
}
};
int main()
{
// option #2 - using available array (??)
int input[5] = {1,2,3,4,5};
int size = sizeof(input)/sizeof(*input);
// array2 has to be of the right size before the call to std::transform
// std::transform does not call push_back. It simply assigns the value to
// the dereferenced iterator.
std::vector<myStruct> array2(size);
std::transform(std::begin(input),
std::end(input),
array2.begin(),
[](int v) -> myStruct { return myStruct(v); });
return(0);
}
的默认构造函数myStruct
可以通过使用std::copy
and来避免std::back_inserter
。
#include <vector>
#include <algorithm>
struct myStruct
{
int value;
myStruct(int input)
{
value = input*input;
}
};
int main()
{
int input[5] = {1,2,3,4,5};
// Create an empty vector.
std::vector<myStruct> array2;
// Add items to the vector by using std::copy and std::back_inserter.
std::copy(std::begin(input),
std::end(input),
std::back_inserter(array2));
return(0);
}