Connecting Tech Pros Worldwide Forums | Help | Site Map

declare const array

vishwesha.guttal@gmail.com
Guest
 
Posts: n/a
#1: Apr 23 '07
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


Victor Bazarov
Guest
 
Posts: n/a
#2: Apr 23 '07

re: declare const array


vishwesha.guttal@gmail.com wrote:
Quote:
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
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask


Ivan Vecerina
Guest
 
Posts: n/a
#3: Apr 24 '07

re: declare const array


<vishwesha.guttal@gmail.comwrote in message
news:1177360267.063205.287510@b58g2000hsg.googlegr oups.com...
: 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<doubledata( (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[i] however you'd like
}
}

hth, Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <http://www.brainbench.com

Closed Thread