在 C + + 中,如何从向量的最后一个元素得到一个字段?

我有一个结构的矢量 VEC。这种结构具有元素 int a, int b, int c。我想赋予一些 int var元素 c,从一个向量的最后一个结构。请你能给我提供这个简单的解决方案吗?我要像这样排成一圈:

var = vec.end().c;
127078 次浏览

Use back():

var = vec.back().c;

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.

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!

You can simply use back as it returns a reference to the last element.
var = vec.back().c

You can use the std:vector<T>:back() function, e.g. vec.back().c. See http://www.cplusplus.com/reference/vector/vector/back/

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.

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.

The following code works for me.

int var;
var =  *(std::end(bar)-1);
std::cout<<var<<std::endl;