[英]How to get the end of a vector and assign it to a string
I want to get the last element of the vector and then assign it to a string but I seem to have problems. 我想获取向量的最后一个元素,然后将其分配给字符串,但似乎有问题。
Imagine this vector has already been filled but I do not know how much so I tried to do this. 想象一下,这个向量已经被填满了,但是我不知道有多少,所以我尝试这样做。
std::vector<std::string> vec;
std::string s = vec.end();
Would a loop work and then just get the last index ? 循环是否有效,然后获取最后一个索引?
This did not work so is there a way to get the end of a vector? 这没有用,所以有没有办法得到向量的结尾?
EDIT------ 编辑 - - -
out.push_back(r.validateR(str));
appendCustomizedOutput = out.back();
DCS_LOG_DEBUG("END " << appendCustomizedOutput);
split(test,appendCustomizedOutput,boost::is_any_of("\n"));
DCS_LOG_DEBUG("END " << test[0]);
When i try to print test[0] nothing is printed and i do not know why ? 当我尝试打印test [0]时,什么也没打印,我也不知道为什么?
vector::end()
returns an iterator that is one beyond the last real element in the vector (it's used primarily for checking while iterating). vector::end()
返回一个迭代器,该迭代器超出向量中的最后一个实数元素(它主要用于迭代时的检查)。
Best way would be: 最好的方法是:
std::string s = vec.back(); // last item
As @JamesKanze and @PeterWood says, don't forget to check for empty vector - else it's undefined behaviour... 正如@JamesKanze和@PeterWood所说的,不要忘记检查空向量-否则它是不确定的行为...
That's what vec.back()
is for. 这就是
vec.back()
目的。 Just make sure that the vector isn't empty first. 只需确保向量不为空即可。
Use vec.back()
to get a reference to the last element. 使用
vec.back()
获取对最后一个元素的引用。 Use vec.pop_back()
to remove the last element (without returning it). 使用
vec.pop_back()
删除最后一个元素(不返回它)。
container.end()
(or whatever kind of container) will return an iterator to the end of the container. container.end()
(或任何种类的容器)将迭代器返回到容器的末尾。 To get the last item in the container, you want container.back()
instead: 要获取容器中的最后一项,您需要使用
container.back()
:
std::string s = vec.back();
end()
returns an iterator referring to the past-the-end element in the vector container. end()
返回一个迭代器,该迭代器引用向量容器中的past-the-end元素。 You need back()
: it returns a reference to the last element in the vector container. 您需要
back()
:它返回对向量容器中最后一个元素的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.