declare const array

V

vishwesha.guttal

Hi,

I am having troble declaring a const array. If the array size is
small, then one can do as follows:

const double array[5] = {1, 2, 3, 4, 5};

What if I have an array of size say 1000 or 10000 which, lets say, I
am reading from a data file? Then manually entering the values is
impossible. So how do I declare such a constant array?

thanks..
Vishwesha
 
V

Victor Bazarov

I am having troble declaring a const array. If the array size is
small, then one can do as follows:

const double array[5] = {1, 2, 3, 4, 5};

What if I have an array of size say 1000 or 10000 which, lets say, I
am reading from a data file? Then manually entering the values is
impossible. So how do I declare such a constant array?

When are you readin ghtme from a data file? Run-time?

If you're concerned with protecting the contents from some accidental
change, you could use the reference trick:

double my_non_const_array[100000];
int dummy = read_array_from_file(my_non_const_array);
double const (&array)[100000] = my_non_const_array;

which will still allow you to use 'array' in your C++ code, and the
type of elements will be 'const double'.

V
 
I

Ivan Vecerina

: I am having troble declaring a const array. If the array size is
: small, then one can do as follows:
:
: const double array[5] = {1, 2, 3, 4, 5};
:
: What if I have an array of size say 1000 or 10000 which, lets say, I
: am reading from a data file? Then manually entering the values is
: impossible. So how do I declare such a constant array?

Use an std::vector to store data read from the file, then use
a "const-pointer to const" referring to its first element.

Consider:

#include <vector>
#include <fstream>
#include <iterator>
#include <cstddef>

int main()
{
std::ifstream src("srcFileName");
std::vector<double> data( (std::istream_iterator<double>(src)),
std::istream_iterator<double>() );

double const* const pItems = &data.front();
std::size_t nItems = data.size();

for( std::size_t i=0 ; i<nItems ; ++i )
{
// use value of pItems however you'd like
}
}

hth, Ivan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,040
Latest member
papereejit

Latest Threads

Top