0

In my code I have:

struct datapoint
{
  double energy;
  double probability;
};

Which is later put into a vector like so:

std::vector<datapoint> spectrum(71,0);

spectrum[0].energy = 0.937729;
spectrum[0].probability = 0.0022582628449311468;
spectrum[1].energy = 1.875458;
spectrum[1].probability = 0.0033531784328108922;
...

However, at compile time, for the line

std::vector<datapoint> spectrum(71,0);

I receive the error

/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/bits/stl_vector.h: In member function âvoid std::vector<_Tp, _Alloc>::_M_initialize_dispatch(_Integer, _Integer, std::__true_type) [with _Integer = int, _Tp = datapoint, _Alloc = std::allocator<datapoint>]â:
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/bits/stl_vector.h:303:   instantiated from âstd::vector<_Tp, _Alloc>::vector(_InputIterator, _InputIterator, const _Alloc&) [with _InputIterator = int, _Tp = datapoint, _Alloc = std::allocator<datapoint>]â
/src/PrimaryGeneratorAction.cc:74:   instantiated from here
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/bits/stl_vector.h:991: error: no matching function for call to âstd::vector<datapoint, std::allocator<datapoint> >::_M_fill_initialize(size_t, int&)â

I'm a bit confused as I have done this before.

Csq
  • 5,775
  • 6
  • 26
  • 39

2 Answers2

3

You are trying to invoke the fill-constructor of vector:

explicit vector (size_type n, const value_type& val = value_type(),
                 const allocator_type& alloc = allocator_type());

But 0 is not a valid value of type datapoint.

us2012
  • 16,083
  • 3
  • 46
  • 62
1
struct datapoint
{
    double energy;
    double probability;
    datapoint():energy(0.0), probability (0.0)
    {}
};

then std::vector spectrum(71);

Have fun,

blackmath
  • 242
  • 1
  • 10
  • 1
    Good with C++11, careful with older versions where defining a constructor means that the type is no longer POD - other parts of the code might rely on this. For details, see http://stackoverflow.com/questions/6496545/trivial-vs-standard-layout-vs-pod . – us2012 Feb 14 '13 at 20:16
  • How can other parts reply on this? should not this be their mistake to consider plain old data style? – blackmath Feb 14 '13 at 20:23
  • What kind of argument is this? Say you're working with a big system, external libraries, etc - you can't exactly be like "I'm gonna change this and I don't care if it breaks because it's everyone else's fault for not doing it the other way in the first place". – us2012 Feb 14 '13 at 20:26