I have a struct array like this:
struct VERTEX_FMT
{
float x, y, z, u, v;
const static DWORD FVF = (D3DFVF_XYZ | D3DFVF_TEX1);
};
VERTEX_FMT vertices[] = {
{-1.0f, -1.0f, 0.0f, 0.0f, 0.0f},
{-1.0f, 1.0f, 0.0f, 0.0f, 1.0f},
{ 1.0f, -1.0f, 0.0f, 1.0f, 0.0f},
{ 1.0f, 1.0f, 0.0f, 1.0f, 1.0f},
};
Is there an easy to way assign the struct arr开发者_开发百科ay a new value in C++.
Only if you wrap the array in another struct
. Arrays are pretty broken in C, and C++ decided that std::vector
was sufficient, and that any attempt to fix C style arrays either wouldn't go far enough to make a difference, or would break compatibility to a point where you couldn't talk of C style arrays any more.
For POD arrays like yours, memcpy
is by far the simplest solution. For more complicated cases, and even most cases of arrays of struct
s like yours, you should probably consider using std::vector
instead. Or a mixture: use the C style arrays for static, initialized arrays such as the one you show, so that the compiler will count the number of elements for you, but use std::vector
for anything which isn't completely initialized in the definition, or which is the target of an assignment. It's easy to construct the std::vector
from a C style array using the two iterator constructor of std::vector
, so there's no real inconvenience in having both types.
if you mean insert a new value, then no - the array is fixed size - you cannot change it easily. You'll have to create a completely new array - what you should really do is look at std::vector
std::vector<VERTEX_FMT> new_array(vertices, vertices + sizeof(vertices)/sizeof(VERTEX_FMT));
// add the new entry in
new_array.push_back(...);
EDIT: based on the comment, it appears that what you want to do is something like:
vertices[2] = {....}; // new values.
Quickest way to do this in the current standard is to use a std::memcpy
or std::copy
, something like:
VERTEX_FMT nv = { ... };
// copy this in
std::memcpy(&vertices[2], &nv, sizeof(nv));
// the line below also works if you want to use purely standard algorithms.
//std::copy(&nv, (&nv) + 1, &vertices[2]);
You can use std::generate, or some other stl algorithm function.
As already said, there are no other ways to do it in the current version c++ (it will be possible in c++0x)
In current standard, you cannot do,
int a[3] = {1,2,3};
a[] = {4,5,6};
But you can definitely get its effect using pointer to an array type,
int a[3] = {1,2,3}, (*p)[3]; // <-- this syntax forces p to point only int[3]
p = &a;
int b[3] = {4,5,6,};
p = &b;
精彩评论