0
const int new_WEIGHT[GENE] = { temp_WEIGHT[0],temp_WEIGHT[1],temp_WEIGHT[2],temp_WEIGHT[3],temp_WEIGHT[4],temp_WEIGHT[5],temp_WEIGHT[6],temp_WEIGHT[7] };

Is there another way, rather than copying all of the array indexes? I mean, somehow another way to copy the array to another constant array? Please help!

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 4
    Use a `std::array`. They allow you to make copies of the entire array. – NathanOliver Apr 20 '21 at 15:58
  • not very clear about what you mean. Any references? – watashiwa chooi Apr 20 '21 at 16:06
  • 1
    There is documentation and some example code here: [https://en.cppreference.com/w/cpp/container/array](https://en.cppreference.com/w/cpp/container/array) – drescherjm Apr 20 '21 at 16:09
  • 2
    I don't see too much point to two constant copies of the same array, They will start the same and because they are constant, they can't be changed. Might as well just use the original – user4581301 Apr 20 '21 at 16:56

1 Answers1

3

You can copy a std::array:

const std::array temp_WEIGHT {1, 2, 3, 4, 5, 6, 7, 8};
const auto new_WEIGHT = temp_WEIGHT;

You can convert (and copy) a C array to a C++ array with to_array:

const int temp_WEIGHT[] = {1, 2, 3, 4, 5, 6, 7, 8};
const auto new_WEIGHT = std::to_array(temp_WEIGHT);

You can access the underlying array with std::array<T,N>::data and the size with std::array<T,N>::size

#include <array>
#include <iostream>

void f(int arr[], std::size_t size) {
    for (std::size_t i = 0; i < size; ++i) {
        arr[i] *= 2;
    }
}

int main() {
    const int temp_WEIGHT[] = {1, 2, 3, 4, 5, 6, 7, 8};
    auto new_WEIGHT = std::to_array(temp_WEIGHT);
    f(new_WEIGHT.data(), new_WEIGHT.size());
    for (const auto &el : new_WEIGHT) {
        std::cout << el << ' ';
    }
}

If you need a reference to a C array you can

#include <array>
#include <iostream>

template<std::size_t SIZE>
void f(int (&arr)[SIZE]) {
    for (auto &el : arr) {
        el *= 2;
    }
}

int main() {
    const int temp_WEIGHT[] = {1, 2, 3, 4, 5, 6, 7, 8};
    auto new_WEIGHT = std::to_array(temp_WEIGHT);
    f(*static_cast<int(*)[new_WEIGHT.size()]>(static_cast<void*>(new_WEIGHT.data())));
    for (const auto &el : new_WEIGHT) {
        std::cout << el << ' ';
    }
}

From Is it legal to cast a pointer to array reference using static_cast in C++? I understand that this is well-defined and legal.

That said I don't see any reason to use C arrays today.