可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have a vector vec of structures. Such a structure has elements int a, int b, int c. I would like to assign to some int var the element c, from the last structure in a vector. Please can you provide me with this simple solution? I'm going circle in line like this:
var = vec.end().c;
回答1:
The immediate answer to your question as to fetching access to the last element in a vector can be accomplished using the back()
member. Such as:
int var = vec.back().c;
Note: If there is a possibility your vector is empty, such a call to back()
causes undefined behavior. In such cases you can check your vector's empty-state prior to using back()
by using the empty()
member:
if (!vec.empty()) var = vec.back().c;
Likely one of these two methods will be applicable for your needs.
回答2:
vec.end()
is an iterator which refers the after-the-end location in the vector. As such, you cannot deference it and access the member values. vec.end()
iterator is always valid, even in an empty vector (in which case vec.end() == vec.begin()
)
If you want to access the last element of your vector use vec.back()
, which returns a reference (and not iterator). Do note however that if the vector is empty, this will lead to an undefined behavior; most likely a crash.
回答3:
Use back()
:
var = vec.back().c;
回答4:
var = vec.back().c;
is what you want.
end()
returns the iterator (not an element) past-the-end of the vector. back()
returns a reference to the last element. It has a counterpart front()
as well.
回答5:
Try this: var = vec.back().c;
Also you may modify your code like:
var = vec.rbegin()->c;
In both versions first make sure that the vector is not empty!
回答6:
You can simply use back
as it returns a reference to the last element.
var = vec.back().c
回答7:
You can use the std:vector<T>:back()
function, e.g. vec.back().c
. See http://www.cplusplus.com/reference/vector/vector/back/