Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我想出了以下片段,但它看起来很hacky。
vector<int> collection; collection.push_back(42); int *pointer = &(*(collection.end()--));
有没有一种简单的方法来获取指向最后插入的元素的指针?
对于std::vector,back()返回对最后一个元素的引用,这&collection.back()就是您所需要的。
std::vector
back()
&collection.back()
在 C++17 中,emplace_back返回对新元素的引用。您可以使用它来代替push_back:
emplace_back
push_back
vector<int> collection; int *pointer = &collection.emplace_back(42);