简体   繁体   中英

Copy and iterate on vector in C++

I try to copy a vector previousVector into another vector currentVector in C++.

My code is below. I want to navigate currentVector and based on condition on values, add element in previousVector . I'm not sure that is the correct way to do.

int ChooseElement(std::vector<Powers>* previousVector) {
    std::vector<Powers> currentVector(*previousVector);
    for(auto iter = currentVector.begin(); iter != currentVector.end(); iter++ ) {
      if(condition on (*iter)) 
        (*previousPowers).push_back(someValue);
    }
    return 0
}

main(int argc, const char * argv[]){
    std::vector<myObjectType> listOfElements;
    myObjectType result = myObjectType(1,2);
    listOfElements.push_back(result);
    result = ChooseElements(&listOfElements);
    return 0;
}

I want to navigate currentVector and based on condition on values, add element in previousVector.

If your intention is to add the element that you're iterating, then that is exactly what std::copy_if is for:

std::copy_if(currentVector.begin(), currentVector.end(),
             std::back_inserter(previousVector), condition_functor);

If you intend to do what your code does, then you don't need currentVector at all because it's values don't appear to be used for anything. What your code does is: it adds someValue to previousVector and does it n times where n is the number of elements in previousVector for which the condition is true. If that's indeed what you intend, then this is a simpler way to do it:

void ChooseElement(std::vector<Powers>& v) {
    auto count = std::count_if(v.begin(), v.end(), condition_functor);
    v.insert(v.end(), count, someValue);
}

Your push_back() should be fine, as currentVector is a deep copy of original vector, so operations on previousVector does not affect it at all. But this method is very ineffective, use temporary vector instead:

int ChooseElement(std::vector<Powers> &previousVector) {
    std::vector<Powers> tmp;
    for(auto iter = previosVector.begin(); iter != previousVector.end(); iter++ )   {
      if(condition on (*iter)) 
        tmp.push_back(someValue);
    }
    std::move( tmp.begin(), tmp.end(), std::back_inserter( previousVector ) );      
    return 0;
}

If you cannot use c++11 replace std::move() with:

   previosVector.insert( previosVector.end(), tmp.begin(), tmp.end() );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM