Initialize vector

  • Thread starter Christian Christmann
  • Start date
C

Christian Christmann

Hi,

I've a header file with the declaration of an int vector:

class BSet
{
[snip]
private :
std::vector<int> data;
[snip]

In the source file I'd like to initialize the vector with DEFSIZE copies
of "0" (where DEFSIZE is an int) within a contructor. My idea was to use
the standard vector constructor "vector<T> v(DEFSIZE,'0')" but all my
attempts failed.

I also used to try:

BSet::BSet()
{
for (int i=0; i < DEFSIZE; i++)
{
data = 0;
}
[snip]

but this results in a "Segmentation fault" when accessing the elements
of the vector data.

Any idea how to use the standard constructor appropriately?

Thanks
Chris
 
S

Sumit Rajan

Christian Christmann said:
Hi,

I've a header file with the declaration of an int vector:

class BSet
{
[snip]
private :
std::vector<int> data;
[snip]

In the source file I'd like to initialize the vector with DEFSIZE copies
of "0" (where DEFSIZE is an int) within a contructor. My idea was to use
the standard vector constructor "vector<T> v(DEFSIZE,'0')" but all my
attempts failed.

I also used to try:

Why is it that I cannot find any clue to the existence of such a constructor
in the class definition above? I'm assuming that it part of the "[snips]"
above. ;-)
BSet::BSet()

Use an initialization list:
BSet::BSet():data(DEFSIZE, 0)
{
}

Regards,
Sumit.
 
S

Sumit Rajan

Christian Christmann said:
I also used to try:

BSet::BSet()
{
for (int i=0; i < DEFSIZE; i++)
{
data = 0;
}
[snip]

but this results in a "Segmentation fault" when accessing the elements
of the vector data.


That is because the elements of "data" you are writing above (in the
for-loop) do not exist at that point. Consider using push_back in case you
want to do something on these lines.

--
 

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,780
Messages
2,569,611
Members
45,277
Latest member
VytoKetoReview

Latest Threads

Top