Home > Software design >  How to avoid copy when i want to move data from stack to vector?
How to avoid copy when i want to move data from stack to vector?

Time:11-17

I have a very-frequently used operation, which need to move data from stack into vector.

let me write a demo code:

void handle(const std::vector<std::vector<std::pair<size_t, double>>> & v) {  // this is my handle data function

}

int main() {
  std::stack<std::vector<std::pair<size_t, double>>> data; // this is my data container, it's a stack
  int cnt = 0;
  std::vector<std::vector<std::pair<size_t, double>>> params(3);
  while (cnt   < 3) {   // assume this handle need 3 data
    const auto & v = data.top();
    params[cnt] = v;  // i think this will involve copy operation
    // and in real scene, i need to keep params in order,
    // so i cant use emplace back, only can use [i]
    data.pop();
  }
  handle(params);
}

can you help on this, how can i avoid copy and speed up my code?

CodePudding user response:

This, your code, will create a copy of the vector.

const auto & v = data.top();
params[cnt] = v;

This will avert the copy, by moving the vector out of data.

auto & v = data.top();
params[cnt] = std::move(v);

Both operations are described, as forms (1) and (2), in cpprefernce.

  • Related