将矢量分成几个的最有效方法

Ang*_*Koh 5 c++ vector c++98

我有以下代码将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());
Run Code Online (Sandbox Code Playgroud)

Ben*_*ley 7

您不应该从vectorOfInterest每次迭代中删除元素.这涉及许多不必要的复制.相反,保持持久迭代器.您还可以避免每次迭代都分配子列表.

vector<CLASS_T>::iterator from = vectorOfInterest.begin();
vector<CLASS_T> subList;

do {
    if(vectorOfInterest.end() - from > blockSize) {    
        subList.assign(from, from + blockSize);
        from += blockSize;    
        OTHERCLASS::doSend(subList);
    }else {            
        subList.assign(from, vectorOfInterest.end());
        subList.resize(blockSize);    
        OTHERCLASS::dosend (subList);    
        vectorOfInterest.clear();
        subList.clear();
    }    
} while ( !vectorOfInterest.empty());
Run Code Online (Sandbox Code Playgroud)