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

泄露秘密 提交于 2019-12-22 03:28:06

问题


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

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!


回答1:


int* ptrToLastOne = &vec.back(); // precondition: !vec.empty()



回答2:


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



回答3:


Some more options:

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

or

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



回答4:


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.



来源:https://stackoverflow.com/questions/3651847/prettier-syntax-for-pointer-to-last-element-stdvector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!