How to read data to build const array?

constvariables cannot be changed after declaration. I know what I can determine const intby:

const int a[5]={0,1,2,3,4};

But the problem is that I don’t know exactly what data is. And reading the data only once is enough, and can I save them in the const array with some pointer operations? I would be grateful if you can give some advice :)

+4
source share
3 answers

Use function:

std::vector<int> readArray()
{
    std::vector<int> array;
    // populate array
    return array;
}

Then:

const std::vector<int> constArray = readArray();

Replace std::vectorwith std::arrayif you know the number of elements in advance.

+4
source

Indeed, you cannot dynamically read data into a const array.

- - const .

, std:: array...

#include <array>
#include <algorithm>
#include <iostream>

int main() {
    std::array<int, 5> writable = {4,3,0,1,2};
    const std::array<int, 5> & readable = writable;

    // you can mutate the writable (and use algorithms...)
    std::sort(writable.begin(), writable.end());

    // readable[0] = 1020; // this would give an error

    // but read access is fine
    for(int i : readable)
        std::cout << i << ' ';
}

(. , " , ", . , , , , . -----, , , buuuut... , , . !)

+3

const:

const auto a = []{
    std::array<int, 5> r;
    std::cout << "Enter " << r.size() << " integers: ";
    std::copy_n(std::istream_iterator<int>(std::cin), r.size(), r.begin());

    return r;
}();

Live On Coliru

int main() { return std::accumulate(a.begin(), a.end(), 0u); }

.

+2

Source: https://habr.com/ru/post/1614238/


All Articles