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

北战南征 提交于 2019-12-05 01:26:53
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());
sharptooth

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.

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