我有一个 vector ,我想使用 STL 算法有效地将 vector 的后半部分分解为另一个 vector 。这是我看到的一种方法,但希望有更高效和简洁的答案,或者至少是使用 STL 算法的答案:
std::vector<Entry> &entries = someFunction();
int numEntries = entries.size();
// Assume numEntries is greater than or equal to 2.
std::vector<Entry> secondEntries;
std::vector<Entry>::iterator halfway = entries.begin() + numEntries / 2;
std::vector<Entry>::iterator endItr = entries.end()
// Copy the second half of the first vector in the second vector:
secondEntries.insert(secondEntries.end(), halfway, endItr);
// Remove the copied entries from the first vector:
entries.erase(halfway, endItr);
最佳答案
退后一步,请记住确保您使用的是具有自己算法的迭代器,而不是(必须)容器。所以如果你有这个:
void foo(const std::vector<Entry>& v) { /* ... */ }
现在你陷入了这种情况:
std::vector<Entry> entries = someFunction();
// have to split entries! make more containers? :(
foo(first_half(entries));
foo(second_half(entries));
考虑改用迭代器:
// or a template, if it doesn't hurt
void foo(std::vector<Entry>::const_iterator first,
std::vector<Entry>::const_iterator second) { /* ... */ }
所以现在您表示范围而不是容器:
std::vector<Entry> entries = someFunction();
// easy to split entries! :)
auto middle = entries.begin() + entries.size() / 2;
foo(entries.begin(), middle);
foo(middle + 1, entries.end());
这限制了您进行的不必要容器和分配的数量。
除此之外,在 C++11 中你可以这样做(其余部分相同):
// *Move* the second half of the first vector in the second vector:
secondEntries.insert(secondEntries.end(),
std::make_move_iterator(halfway),
std::make_move_iterator(endItr));
如果 Entry
有移动构造函数,move_iterator
适配器将确保在插入期间使用它(如果没有,则进行正常复制)。在 C++03 中,您拥有的可能是最好的。
关于c++ - 如何将 vector 的后半部分移动到另一个 vector 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11938889/