std::copy doesn't copy vector in C++

To find all sequences of fixed length which contain only 0 and 1 I use this code:

#include <bits/stdc++.h>

typedef long long int lli;
typedef std::vector<lli> vec_lli;
typedef std::vector<std::string> vec_s;

void print_array(vec_s arr) {
  std::cout << '[';
  int n = arr.size();
  for (size_t i = 0; i < n; i++) {
    std::cout << arr[i];
    if (i < (n - 1)) {
      std::cout << ", ";
    }
  }
  std::cout << ']' << std::endl;
}

vec_s get_variants(int n) {
  vec_s result = {"0", "1"};
  vec_s temp;
  temp.reserve(2);
  result.reserve(2);
  for (int i=0; i < (n - 1); ++i) {
    std::copy(result.begin(), result.end(), temp.end()); // 1
    for (int j=0; j < result.size(); ++j) {
      temp[j] += "0";
      result[j] += "1";
    }
    std::copy(temp.begin(),temp.end(), result.end());
    temp.clear();
  }
  return result;
}

int main(int argc, char const *argv[]) {
  int n;
  std::cin >> n;
  vec_s mb = get_variants(n);
  print_array(mb);
  return 0;
}

But vector temp is empty, before copying in line 1 and after. So, my program's output was [0111, 1111]. What I'm doing wrong?


A more straightforward way than using std::copy is the use of .insert():

temp.insert(temp.end(), result.begin(), result.end()); //1
...
result.insert(result.end(), temp.begin(), temp.end()); // 2nd copy

You are writing to temp.end() and result.end(). These iterators represent "one past the end", and therefore writing to these iterators is Undefined Behavior.

You seem to be looking for std::back_inserter. This will create an iterator that will insert a new element to your container when it is written through.

std::copy(result.begin(), result.end(), std::back_inserter(temp));

While this answers the posted question, there remain other errors in your code leading to Undefined Behavior.