Re: declare const array
<vishwesha.guttal@gmail.com> wrote in message
news:1177360267.063205.287510@b58g2000hsg.googlegroups.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<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[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