jeudi 9 décembre 2021

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?

Aucun commentaire:

Enregistrer un commentaire