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!

4
  • 4
    Use a std::array. They allow you to make copies of the entire array. Commented Apr 20, 2021 at 15:58
  • not very clear about what you mean. Any references? Commented Apr 20, 2021 at 16:06
  • 1
    There is documentation and some example code here: https://en.cppreference.com/w/cpp/container/array Commented Apr 20, 2021 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 Commented Apr 20, 2021 at 16:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.