我想知道是否有更漂亮的语法来获取指向 C++ 向量中最后一个元素的普通指针(不是迭代器)
std::vector<int> vec;
int* ptrToLastOne = &(*(vec.end() - 1)) ;
// the other way I could see was
int* ptrToLastOne2 = &vec[ vec.size()-1 ] ;
但是这两个都不是很好看!
int* ptrToLastOne = &vec.back(); // precondition: !vec.empty()
int* ptrToLast = &(vec.back()); // Assuming the vector is not empty.
还有一些选择:
int* ptrToLast = &*vec.rbegin();
或者
int* ptrToLast = &*boost::prev(vec.end());
没有什么比这更漂亮的了,但是你可以编写一个模板化的辅助函数,它会在内部为你做同样的事情,这样至少调用站点看起来会更干净,并且你会因为错别字而出现错误的可能性更低。
请参阅已接受的非常相似问题的答案以及解决方案的外观。