c ++向量最后元素字段 [英] c++ vector last element field
问题描述
我有一个向量 vec 的结构。这种结构具有元素 int a,int b,int c 。我想分配一些 int var 元素c,从向量中的最后一个结构。请你给我提供这个简单的解决方案?我要按照这样的圈子:
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;
推荐答案
向量中的最后一个元素可以使用 back()
成员来完成。如:
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;
注意:如果有可能你的向量为空, > back()导致未定义的行为。在这种情况下,您可以使用 empty()来检查向量的空状态先使用
/ code> member:
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.
这篇关于c ++向量最后元素字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!