【发布时间】:2014-08-27 06:58:00
【问题描述】:
我有以下代码将 vectorOfInterest 分解成更小的块以发送出去。 此代码正在运行。
但是,当我将 vectorOfInterest 拆分为更小的块时(在 subList 和剩余部分的构造函数中),我会进行复制。 有没有更好的使用移动而不是再次复制数据以获得更好的性能?
请注意,我无法更改 OTHERCLASS::doSend() 的参数
编辑:我使用的是 C++98
int blockSize = 50;
vector <CLASS_T> vectorOfInterest;
// ...<populates vectorOfInterest>
do {
if(vectorOfInterest.size()> blockSize)
vector<CLASS_T>iterator from = vectorOfInterest.begin();
vector<CLASS_T>iterator to = from + blockSize;
//elements are copied again in subList and remainder
//I like to move the elements from vectorOfInterest instead.
vector<CLASS_T> subList (from, to);
vector<CLASS_T> remainder (to, vectorOfInterest.end());
vectorOfInterest.swap(remainder);
OTHERCLASS::doSend (subList); // method which sends sublists in blocks of exactly 50 to external library
}else {
//pad to exactly size 50
vectorOfInterest.resize(blockSize);
OTHERCLASS::dosend (vectorOfInterest); // method which sends sublists in blocks of exactly 50 to external library
vectorOfInterest.clear();
}
while ( !vectorOfInterest.empty());
【问题讨论】:
-
有一些方法可以提高效率,但我能想到的都需要你更改
OTHERCLASS::doSend()(例如,保留boost::shared_ptr<CLASS_T>的向量,以便复制shared_ptrs不复制CLASS_Ts;将一对迭代器传递给OTHERCLASS::doSend(),这样它就无法访问原始元素而不是它们的副本。 -
也许这篇stackoverflow.com/questions/4707012/c-memcpy-vs-stdcopy 的帖子也有帮助。在某些平台上 memcpy 可能更快......但我会选择你的实现