对象安全地将元素从一个向量的末尾移动到另一个向量的末尾
Object-safe move element from the end of a vector to the end of another vector
我是 C++ 的新手。
我研究了很多关于 C++ 的文章以及将 vector 的最后一个元素移动到另一个元素的解决方案,但我仍然不明白该怎么做。
我有两个向量:
std::vector<Person *> persons;
std::vector<Person *> availablePersons;
和功能:
MoveLast() {
std::move(persons.end() - 1, persons.end(), std::back_inserter(availablePersons));
}
但是看起来很长,没有达到预期的效果。
所以我需要简单有效的方法而不丢失内存中的 Person
个对象
向量不包含 Person
对象,它们只包含指针。移动这些指针实际上意味着执行复制。所以你在做两件事,将一个指针复制到一个容器并从另一个容器中删除一个指针。像这样的简单实现应该就是您所需要的:
MoveLast() {
if (!persons.empty()) { // ensure source vector isn't empty
availablePersons.push_back(persons.back()); // copy last element to destination
persons.pop_back(); // remove last element from source
}
}
如果您的向量持有一个支持移动的类型,那么作为优化,您可以将第二行更改为:
availablePersons.push_back(std::move(persons.back())); // move last element to destination
我是 C++ 的新手。
我研究了很多关于 C++ 的文章以及将 vector 的最后一个元素移动到另一个元素的解决方案,但我仍然不明白该怎么做。
我有两个向量:
std::vector<Person *> persons;
std::vector<Person *> availablePersons;
和功能:
MoveLast() {
std::move(persons.end() - 1, persons.end(), std::back_inserter(availablePersons));
}
但是看起来很长,没有达到预期的效果。
所以我需要简单有效的方法而不丢失内存中的 Person
个对象
向量不包含 Person
对象,它们只包含指针。移动这些指针实际上意味着执行复制。所以你在做两件事,将一个指针复制到一个容器并从另一个容器中删除一个指针。像这样的简单实现应该就是您所需要的:
MoveLast() {
if (!persons.empty()) { // ensure source vector isn't empty
availablePersons.push_back(persons.back()); // copy last element to destination
persons.pop_back(); // remove last element from source
}
}
如果您的向量持有一个支持移动的类型,那么作为优化,您可以将第二行更改为:
availablePersons.push_back(std::move(persons.back())); // move last element to destination