EDIT Sorry! This code actually works correctly; I was looking at the wrong error. Thanks to everyone for their input.
I want to be able to directly access the last element of a vector<>
in C++. Currently, I push_back()
a temporary variable (of a custom开发者_开发知识库 type), however I'd much rather put data straight into the vector. The following code is an example of what I'd like to do. It won't compile, but it does a better job of explaining than I do:
typedef struct
{
float colour[3];
}
CustomType
vector<CustomType> customArray;
customArray.push_back(CustomType());
// The hard part - won't work
customArray.back().colour[0] = 1;
I'd like some help with the last line; what's the correct syntax to put data into the most-recently pushed back element in a vector?
Why won't
customArray.back().colour[0] = 1;
work?
It does work! Try again :)
back()
returns a reference to the last item of the vector, your code is correct apart from a small syntax error.
customArray.size() - 1
is the index of the last item that was added to the vector
customArray[customArray.size()-1].color[0]=1
should work.
[As Oli and interjay et al have commented, the back()
method will work if you correct the syntax error]
Do you mean something like this:
// Construct vector with `NUM_ELEMENTS` entries
vector<CustomType> customArray(NUM_ELEMENTS);
// Now you can access them directly
customArray[0].colour[0] = 1;
精彩评论