By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,327 Members | 1,785 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,327 IT Pros & Developers. It's quick & easy.

Initialize vector

P: n/a
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[i] = 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


Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a

"Christian Christmann" <pl*****@yahoo.de> wrote in message
news:3a*************@individual.net...
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.
--
Sumit Rajan <su*********@gmail.com>

Jul 23 '05 #2

P: n/a

"Christian Christmann" <pl*****@yahoo.de> wrote in message
news:3a*************@individual.net...
I also used to try:

BSet::BSet()
{
for (int i=0; i < DEFSIZE; i++)
{
data[i] = 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.

--
Sumit Rajan <su*********@gmail.com>

Any idea how to use the standard constructor appropriately?

Thanks
Chris

Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.