简体   繁体   English

“指向最后一个元素的指针”的漂亮语法,std :: vector?

[英]Prettier syntax for “pointer to last element”, std::vector?

I'm wondering if there is prettier syntax for this to get a normal pointer (not an iterator) to the last element in a C++ vector 我想知道是否有更漂亮的语法来获取指向C ++向量中最后一个元素的普通指针(而不是迭代器)

std::vector<int> vec;

int* ptrToLastOne = &(*(vec.end() - 1)) ;

// the other way I could see was
int* ptrToLastOne2 = &vec[ vec.size()-1 ] ;

But these are both not very nice looking! 但是这些看起来都不是很好!

int* ptrToLastOne = &vec.back(); // precondition: !vec.empty()
int* ptrToLast = &(vec.back()); // Assuming the vector is not empty.

Some more options: 其他一些选择:

int* ptrToLast = &*vec.rbegin();

or 要么

int* ptrToLast = &*boost::prev(vec.end());

Nothing much prettier for that, but you can write a templated helper function that will do the same for you internally, and this way at least the call sites will look much cleaner and you'll get lower probability for planting errors through typos. 没有什么比这漂亮的了,但是您可以编写一个模板化的帮助器函数,在内部为您做同样的事情,这样,至少调用站点看起来会更加整洁,并且您通过错别字植入错误的可能性会更低。

See the accepted answer to a very similar question and what the solution might look like. 查看一个非常相似的问题的公认答案 ,以及解决方案的外观。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM