开发者

Insert properties into last element in a vector [closed]

开发者 https://www.devze.com 2023-03-27 19:59 出处:网络
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time,or an extraordinarily narrow situation that is not generally applic
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 10 years ago.

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消