简体   繁体   中英

Optimizing vector assignment c++

I have a function which returns a vector. Let's name it v . I use v.begin() and v.end() in a function. How could I make using .begin() and .end() without creation a new vector v2 to store the previous vector v so I can get access to methods?

Here's what I mean:

std::vector<int> merge(...) {
    ...
    return v;
}
void mergeSort(...) {
    ...
    std::vector<int> v2;
    v2 = merge(...);
    I_need_this = v2.begin();
    And_I_really_need_this_too = v2.end();
    ...
}

The best way to optimize assignment is to not assign at all, but use initialization

std::vector<int> v2 = merge(...);

It is almost certain that the compiler will create v directly into v2 , without any copying.

A common pattern when you need to return collections, in order to prevent them from being copied, is to pass the collection by non-const reference and to make the changes to the original. This means that the caller is responsible for instantiating the collection, not the callee, and as such no copy ever occurs. Here's an example:

void merge(std::vector<int> & result, ...) {

    // Do changes to result
    ...
}
void mergeSort(...) {
    ...
    std::vector<int> v;
    merge(v, ...);

    // This is OK now
    I_need_this = v.begin();
    And_I_really_need_this_too = v.end();
    ...
}

You can bind your vector temporary to a reference:

extern std::vector<int> f();

auto&& x = f();
std::sort(x.begin(), x.end());  // example

You have a number of options:

  1. Don't worry about it. Performance is usually not that important.

  2. Turn on optimization (you would be amazed how many "optimization" questions on SO are solved by that step).

  3. Upgrade to a C++11 compiler. The compiler should use the move assignment operator for vector, which is very efficient (any decent library will transfers the internally allocated array from the temporary to the target with no memory allocation and no copying of elements).

  4. If you can't use a C++11 compiler, or you've measured, and this is still a performance bottleneck, switch to initialization as suggested by Bo Person in his answer

  5. If you've measured, and this is still a performance bottleneck, and you can't get your compiler to implement the RVO, then you have no choice but to pass the vector in by value as suggest by André Fratelli in his answer

If we step back from discussing optimization, and discuss writing good, clear, code, then I would recommend in order of preference:

  • Initialization from function result
  • Assignment from function result
  • Pass in vector to be filled.

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