c++ vector last element field

匿名 (未验证) 提交于 2019-12-03 02:55:01

问题:

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/



转载请标明出处:c++ vector last element field
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!