如何将向量的后半部分移动到另一个向量? [英] How to move the later half of a vector into another vector?
问题描述
我有一个向量,我想使用STL算法将向量的后半部分有效地分解为另一个向量.这是我看到的一种方法,但是希望有更有效和简洁的答案,或者至少使用stl算法:
I have a vector and I would like to efficiently break out the second half of the vector into another vector using STL algorithms. Here is one way I see to do this, but expect there are more efficient and succinct answers, or at the least, one that uses the stl algorithms:
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);
推荐答案
退后一步,请记住要确保您使用自己的算法而不是(必要的)容器来处理迭代器.所以,如果你有这个:
Taking a step back, keep in mind to make sure that you're working with iterators with your own algorithms, and not (necessarily) containers. So if you have this:
void foo(const std::vector<Entry>& v) { /* ... */ }
现在您陷入了这种情况:
And now you're stuck in this situation:
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) { /* ... */ }
所以现在您表示范围而不是容器:
So now you denote ranges and not containers:
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());
这限制了您不必要的容器和分配的数量.
This limits the number of unnecessary containers and allocations you make.
通过这种方式,在C ++ 11中,您可以做到这一点(其余部分相同):
With that out of the way, in C++11 you can do this (rest is the same):
// *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构造函数,则 move_iterator
适配器将确保在插入过程中使用它(如果未制作普通副本).在C ++ 03中,您拥有的可能是最好的.
If Entry
has a move constructor, the move_iterator
adapter will ensure that it is used during the insertion (if it doesn't a normal copy is made). In C++03, what you have is probably best.
这篇关于如何将向量的后半部分移动到另一个向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!