469,917 Members | 1,631 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,917 developers. It's quick & easy.

new, delete, STL

I'm having a problem allocating some elements of a vector then deleting
them.

Basicaly I have something like this:
class base
{
private:
std::vector<object> V;
//std::vector<*object> V;

public:

void addObject()
{
object *temp = new object;
V.push_back(*temp);

//V.push_back(new object);
}
void removeObject(index)
{
delete &V[index];
V.erase(V.begin() + index);

//delete V[index];
//V.erase(V.begin() + index);
}

};

the commented line is where I used the pointerized version. In the first
case the object's destructor gets called twice(I suppose because when I call
addObject the local variable goes out of scope(any way to prevent this) and
in the second case it doesn't get called at all ;/

I'd rather not use a vector of pointers though... I thought maybe I could
declare the object *temp as static but this seems to be kinda a hack... I
just need a way to say "don't call the destructor for this local object when
it goes out of scope" or something.

Any ideas?

Jon
Aug 29 '05 #1
35 2419
"Jon Slaughter" <Jo***********@Hotmail.com> wrote in message
news:11*************@corp.supernews.com...
I'm having a problem allocating some elements of a vector then deleting
them.
That's because you are using operator new too much.

Basicaly I have something like this:
class base
{
private:
std::vector<object> V;
//std::vector<*object> V;

public:

void addObject()
{
object *temp = new object;
V.push_back(*temp);

//V.push_back(new object);
}
void removeObject(index)
{
delete &V[index];
V.erase(V.begin() + index);

//delete V[index];
//V.erase(V.begin() + index);
}

};
[snip]
Jon


class base
{
private:
std::vector<object> V;

public:
void addObject()
{
V.push_back(object());
}

void removeObject(index)
{
V.erase(V.begin() + index);
}
};

--
Cy
http://home.rochester.rr.com/cyhome/
Aug 30 '05 #2

"Jon Slaughter" <Jo***********@Hotmail.com> wrote in message
news:11*************@corp.supernews.com...
I'm having a problem allocating some elements of a vector then deleting
them.
Really, I find that surprising, since the std::vector
container does all allocations for you automatically.

Basicaly I have something like this:
class base
{
private:
std::vector<object> V;
//std::vector<*object> V;

public:

void addObject()
{
object *temp = new object;
V.push_back(*temp);
Replace previous two lines with:

V.push_back(object());

As I recently wrote in another message, I don't understand
why so many folks feel they need to use 'new' when they really
dont. :-)

//V.push_back(new object);
}
void removeObject(index)
This won't compile. You didn't specify the type of the
parameter 'index'. In this case it should be:

void removeObject(std::vector<object>::size_type)
{
delete &V[index];
V.erase(V.begin() + index);

//delete V[index];
//V.erase(V.begin() + index);
Replace all that with:

if(!V.empty()) // to prevent possible UB
V.erase(V.begin() + index); }

};

the commented line is where I used the pointerized version. In the first
case the object's destructor gets called twice(I suppose because when I
call addObject the local variable goes out of scope(any way to prevent
this) and in the second case it doesn't get called at all ;/

I'd rather not use a vector of pointers though... I thought maybe I could
declare the object *temp as static but this seems to be kinda a hack... I
just need a way to say "don't call the destructor for this local object
when it goes out of scope" or something.


No, don't try to circumvent the way the language works, better
to understand it and use it in the intended ways.

-Mike
Aug 30 '05 #3

"Cy Edmunds" <ce******@spamless.rochester.rr.com> wrote in message
news:Ce*******************@twister.nyroc.rr.com...
"Jon Slaughter" <Jo***********@Hotmail.com> wrote in message
news:11*************@corp.supernews.com...
I'm having a problem allocating some elements of a vector then deleting
them.
That's because you are using operator new too much.


Agreed. And too many people seem to be doing so. :-)

void removeObject(index)
{
if(!V.empty())
V.erase(V.begin() + index);
}
};


-Mike
Aug 30 '05 #4
Mike Wahler wrote:

if(!V.empty())

V.erase(V.begin() + index);
}
};


if (!V.empty() && index < V.size())

But only if the specification calls for it.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Aug 30 '05 #5
"Pete Becker" <pe********@acm.org> wrote in message
news:4Y*****************************************@r cn.net...
Mike Wahler wrote:

if(!V.empty())

V.erase(V.begin() + index);
}
};


if (!V.empty() && index < V.size())

But only if the specification calls for it.


My mind is going, Dave... I can feeel it .... :-)

Note to self: Test, Test, Test. :-)

Thanks, Pete.

-Mike
Aug 30 '05 #6
Mike Wahler wrote:
As I recently wrote in another message, I don't understand
why so many folks feel they need to use 'new' when they really
dont. :-)


Coming from Java or VB? When I code Java, I have the reverse problem,
coming from C++, I tend *not* to use new enough.

Aug 30 '05 #7
Ok then, can some one explain what is going on here then? this is
contradictory to what you guys have said to do to get it to work(cause it
doesn't):

The output is

Object being created
Object being removed
Object being removed
Object being removed

I don't understand how the destructor can be called 3 times and the
constructor called only once(so there should be only one instance of the
object and after the first call of the destructor the instance should be
gone and no more destructor to call).
#include "stdafx.h"

#include <vector>

#include <iostream>

class object

{

public:

object()

{

std::cout << "Object being created\n";

};

~object()

{

std::cout << "Object being removed\n";

};

};

class test

{

private:

std::vector<object> Objects;

public:

test(){ };

void Add()

{

Objects.push_back(object()); // outputs 3 lines Object being created \n
Object being removed \n Object being removed \n

};

void Remove()

{

Objects.erase(Objects.begin()); // outputs one line Object being removed

};

~test() {};

};

int main(int argc, _TCHAR* argv[])

{

test Test;

Test.Add();

Test.Remove();

return 0;

}
Aug 30 '05 #8
red floyd wrote:
Mike Wahler wrote:
As I recently wrote in another message, I don't understand
why so many folks feel they need to use 'new' when they really
dont. :-)

Clarification:
Coming from Java or VB? When I code Java, I have the reverse problem,
coming from C++, I tend *not* to use new enough.


I meant, "maybe they are coming from Java or VB".

Aug 30 '05 #9
// test1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <vector>
#include <iostream>

class object
{
public:
object()
{
std::cout << "Object being created\n";
};
~object()
{
std::cout << "Object being removed\n";
};
};
class test
{
private:
std::vector<object> Objects;
public:
test(){ };
void Add()
{
static object *o = new object; // prints "object being created"
Objects.insert(Objects.begin(), 1, *o); // prints "object being removed"
// Objects.push_back(*o); // same

// same problem if one doesn't use the static pointer method i.e.
Objects.push_Back(object()); does exact same thing

};
void Remove()
{
Objects.erase(Objects.begin());
// crashes debugger
};
~test() {};
};
int main(int argc, _TCHAR* argv[])
{
//object *o = new object;
//delete o;
// code above works exactly as its suppose to
test Test;
Test.Add();
Test.Remove();

return 0;
}
Any ideas?
Aug 30 '05 #10

"Jon Slaughter" <Jo***********@Hotmail.com> wrote in message
news:11*************@corp.supernews.com...
Ok then, can some one explain what is going on here then? this is
contradictory to what you guys have said to do to get it to work(cause it
doesn't):
Yes, it does work. Why do you think it doesn't?

The output is

Object being created
Object being removed
Object being removed
Object being removed
This is only the output you told the program to give
(but there are other things happening which you did
not intercept with your 'cout' statements.)

However (after removing the nonstandard stuff and a syntax error)
after compiling your code, I get output of:

Object being created
Object being removed
Object being removed

Which is what I'd expect.

I don't understand how the destructor can be called 3 times and the
constructor called only once(so there should be only one instance of the
object and after the first call of the destructor the instance should be
gone and no more destructor to call).
Despite what your output says, an 'object' constructor is being
called twice, and a destructor twice. What you're missing is
that it isn't the *default* constructor getting called twice --
one call is to the default constructor, and the other is to the
copy constructor (since you didn't define one,the compiler synthesized
one for you).

Read about the standard containers' 'copy semantics'.

(After reading my notes embedded in your code, see my
example which follows your code.)
#include "stdafx.h"
No such header in standard C++, and you don't need it to
demonstrate your problem.

#include <vector>

#include <iostream>

class object

{

public:

object()

{

std::cout << "Object being created\n";

};
You don't need a semicolon after the closing brace of a function.
Only after a class definition's closing brace.

~object()

{

std::cout << "Object being removed\n";

};

};

class test

{

private:

std::vector<object> Objects;

public:

test(){ };
You don't need this constructor.

void Add()

{

Objects.push_back(object()); // outputs 3 lines Object being created \n
Object being removed \n Object being removed \n

};

void Remove()

{

Objects.erase(Objects.begin()); // outputs one line Object being removed

};

~test() {};
You don't need this destructor.

};

int main(int argc, _TCHAR* argv[])
There's no such type as _TCHAR in standard C++. ANd your
program does not use command-line arguments anyway.

And please indent your code, otherwise it's rather hard to follow.

{

test Test;

Test.Add();

Test.Remove();

return 0;

}


#include <vector>
#include <iostream>

class object
{
public:
object() { std::cout << "Object being created\n"; }
object(const object&) { std::cout << "Object being created\n"; }
~object() { std::cout << "Object being removed\n"; }
};

class test
{
private:
std::vector<object> Objects;
public:
void Add() { Objects.push_back(object()); }
void Remove() { Objects.erase(Objects.begin()); }
};

int main()
{
test Test;
Test.Add();
Test.Remove();
return 0;
}

Output:

Object being created
Object being created
Object being removed
Object being removed

The first 'created' message refers to the default ctor
getting called for the temporary object which is created
by the expression 'object()' in the statement:

Objects.push_back(object());

The second 'created' message refers to the copy ctor
getting called when the 'push_back()' function makes
a copy of your object to store in the vector.

The first 'removed' message refers to the destructor
getting called when the temporary object (created by
'push_back()' gets destroyed.

The second 'removed' message refers to the destructor
getting called when 'Test.Remove()' calls 'vector::erase()'.

-Mike
Aug 30 '05 #11

"Jon Slaughter" <Jo***********@Hotmail.com> wrote in message
news:11*************@corp.supernews.com...
// test1.cpp : Defines the entry point for the console application.
//
[snip (an attempt to use operator 'new' to fix a 'problem'
to which it is completely unrelated.) ]
Any ideas?


Yes. Stop guessing and read a good C++ text. (See my
other post this thread for explanation of your specific
example's behavior.)

-Mike
Aug 30 '05 #12

"Mike Wahler" <mk******@mkwahler.net> wrote in message
news:Im*****************@newsread1.news.pas.earthl ink.net...

"Jon Slaughter" <Jo***********@Hotmail.com> wrote in message
news:11*************@corp.supernews.com...
// test1.cpp : Defines the entry point for the console application.
//


[snip (an attempt to use operator 'new' to fix a 'problem'
to which it is completely unrelated.) ]
Any ideas?


Yes. Stop guessing and read a good C++ text. (See my
other post this thread for explanation of your specific
example's behavior.)

-Mike


You know... you are pretty arrogant... if you get so worked up over helping
then why do it? I didn't ask for your specific help and if you are going to
be an asshole about it then don't offer it.
Aug 30 '05 #13

"Mike Wahler" <mk******@mkwahler.net> wrote in message
news:ek****************@newsread1.news.pas.earthli nk.net...

"Jon Slaughter" <Jo***********@Hotmail.com> wrote in message
news:11*************@corp.supernews.com...
Ok then, can some one explain what is going on here then? this is
contradictory to what you guys have said to do to get it to work(cause it
doesn't):
Yes, it does work. Why do you think it doesn't?


Nope, doesn't work.. sorry.. an object's destructor should be only called
once and no more than once. If STL is copying the object and destorying the
first copy then thats all you had to say...

The output is

Object being created
Object being removed
Object being removed
Object being removed


This is only the output you told the program to give
(but there are other things happening which you did
not intercept with your 'cout' statements.)

However (after removing the nonstandard stuff and a syntax error)
after compiling your code, I get output of:


there was no syntax error... it compiled for me perfectly and I copied the
code directly.

Object being created
Object being removed
Object being removed

Which is what I'd expect.
Hmm. being removed twice? you expect that?

I don't understand how the destructor can be called 3 times and the
constructor called only once(so there should be only one instance of the
object and after the first call of the destructor the instance should be
gone and no more destructor to call).


Despite what your output says, an 'object' constructor is being
called twice, and a destructor twice. What you're missing is
that it isn't the *default* constructor getting called twice --
one call is to the default constructor, and the other is to the
copy constructor (since you didn't define one,the compiler synthesized
one for you).


ok, thats all you had to say in the first place.. .very simple. I don't know
much about STL and copy constructors in the first place and all you had to
do was mention that and there would have been no problems. Now that I know
that STL is copying the objects I prefer not to use it. Its a waste of time
for it to copy them in my situation.
Read about the standard containers' 'copy semantics'.
(After reading my notes embedded in your code, see my
example which follows your code.)
#include "stdafx.h"
No such header in standard C++, and you don't need it to
demonstrate your problem.


Um.. jesus christ.. who cares then? you must hate people that use XP and VS
then because just about every post you have been an ass about stuff like
this(first off the OP was just more like psuedo code and not ment to compile
but to get my problem across)

#include <vector>

#include <iostream>

class object

{

public:

object()

{

std::cout << "Object being created\n";

};


You don't need a semicolon after the closing brace of a function.
Only after a class definition's closing brace.


UM, it doesnt' freaken matter if you put it there or not... so why bother?
stop being an ass.

~object()

{

std::cout << "Object being removed\n";

};

};

class test

{

private:

std::vector<object> Objects;

public:

test(){ };
You don't need this constructor.


SO? doesn't hurt anything either. stop being an ass.

void Add()

{

Objects.push_back(object()); // outputs 3 lines Object being created \n
Object being removed \n Object being removed \n

};

void Remove()

{

Objects.erase(Objects.begin()); // outputs one line Object being removed

};

~test() {};
You don't need this destructor.


ass!

};

int main(int argc, _TCHAR* argv[])
There's no such type as _TCHAR in standard C++. ANd your
program does not use command-line arguments anyway.

And please indent your code, otherwise it's rather hard to follow.


My code is perfectly indented but when I copyed it over the formatting got
left behind(Because I first had to convert it to rich text then back to
plain text because thef irst insertion copied all the formatting and special
character and double spacing crap that made it hard to follow(even though I
know it was going to turn into normal plain text when I posted it))

{

test Test;

Test.Add();

Test.Remove();

return 0;

}
#include <vector>
#include <iostream>

class object
{
public:
object() { std::cout << "Object being created\n"; }
object(const object&) { std::cout << "Object being created\n"; }
~object() { std::cout << "Object being removed\n"; }
};

class test
{
private:
std::vector<object> Objects;
public:
void Add() { Objects.push_back(object()); }
void Remove() { Objects.erase(Objects.begin()); }
};

int main()
{
test Test;
Test.Add();
Test.Remove();
return 0;
}

Output:

Object being created
Object being created
Object being removed
Object being removed

The first 'created' message refers to the default ctor
getting called for the temporary object which is created
by the expression 'object()' in the statement:


Yes, I see that now and if you would have said that in the first place we
could have saved each other a lot more time... all you had to do was mention
that STL copies the object to a new one in its container and I would have
completely understood... but you assume I am a complete idiot and have no
idea about anything.

Objects.push_back(object());

The second 'created' message refers to the copy ctor
getting called when the 'push_back()' function makes
a copy of your object to store in the vector.

The first 'removed' message refers to the destructor
getting called when the temporary object (created by
'push_back()' gets destroyed.

The second 'removed' message refers to the destructor
getting called when 'Test.Remove()' calls 'vector::erase()'.

-Mike


Well, for future reference why don't you just not reply to my messages?
Just because you think your the god of programming doesn't mean you have to
treat others like idiots.


Aug 30 '05 #14
Kev
"Mike Wahler" <mk******@mkwahler.net> wrote in news:tFNQe.4747$z2.822
@newsread3.news.pas.earthlink.net:
My mind is going, Dave... I can feeel it .... :-)


Daisy, Daisy, give me your answer do....
Aug 30 '05 #15
>
#include <vector>
#include <iostream>

class object
{
public:
object() { std::cout << "Object being created\n"; }
object(const object&) { std::cout << "Object being created\n"; }
~object() { std::cout << "Object being removed\n"; }
};

class test
{
private:
std::vector<object> Objects;
public:
void Add() { Objects.push_back(object()); }
void Remove() { Objects.erase(Objects.begin()); }
};

int main()
{
test Test;
Test.Add();
Test.Remove();
return 0;
}

Output:

Object being created
Object being created
Object being removed
Object being removed

BTW, copying and pasting your code directly gives the output of(I did not
change a damn thing either).

Object being created
Object being created
Object being created
Object being removed
Object being removed
Object being removed
Aug 30 '05 #16
After changing your code to
// test1.cpp : Defines the entry point for the console application.

//

#include <vector>

#include <iostream>

class object

{

public:

object() { std::cout << "Object being created\n"; }

object(const object&) { std::cout << "Object being copied\n"; }

~object() { std::cout << "Object being removed\n"; }

};

class test

{

private:

std::vector<object> Objects;

public:

void Add() { Objects.push_back(object()); }

void Remove() { Objects.erase(Objects.begin()); }

};

int main()

{

test Test;

Test.Add();

Test.Remove();

return 0;

}



the output is

Object being created
Object being copied
Object being copied
Object being removed
Object being removed
Object being removed


Hell if I know why that one line of code causes the object to be copied
twice... and I doubt I'll find the answer in the shity STL documents you
refer to.
Aug 30 '05 #17
To be even more clear:

// test1.cpp : Defines the entry point for the console application.

//

#include <vector>

#include <iostream>

class object

{

public:

object() { std::cout << "Object being created\n"; }

object(const object&) { std::cout << "Object being copied\n"; }

~object() { std::cout << "Object being removed\n"; }

};

class test

{

private:

std::vector<object> Objects;

public:

void Add() { std::cout << "Test.Add() {\n";

Objects.push_back(object()); std::cout << "Test.Add() }\n"; }

void Remove() { std::cout << "Test.Remove() {\n";

Objects.erase(Objects.begin()); std::cout << "Test.Remove() }\n"; }

};

int main()

{

test Test;

Test.Add();

Test.Remove();

return 0;

}

gives an output of

Test.Add() {
Object being created
Object being copied
Object being copied
Object being removed
Object being removed
Test.Add() }
Test.Remove() {
Object being removed
Test.Remove() }


So there are several problems with this... first its a waste of time and
resource(even though it is freed almost immediately) to create an empty
instance of an object just so it can be immediately copied then freed.
Second, atleast in my case, it is copying the damn thing twice and if the
object happens to be very large then this could be a huge waste. Maybe I
will try this with gcc and see what I get. While I can possibly live with
one extraneous copy I can't/won't live with two.




Aug 30 '05 #18
The explanation is probably very simple. std::vector is basicly
mimicking array semantics for memory storage, looks like a duck, sounds
like a duck.. walks like a duck, anyway..

When vector runs out of capacity, it is grown.. when vector is grown
new objects are being created, and existing ones are *copied* to the
new storage that is being allocated. It is not defined as far as I can
remember how large the capacity of a vector is initially, and I don't
remember liking to read Dinkumware's (whose implementation you are
currently using) code very much (sorry DW).

The small vectors rarely can both, efficient in runtime and memory
footprint. If they are runtime efficient then it means they need some
larger constant as initial capacity, which wastes memory and
vice-versa. In this context, how would you implement your Standard
Library's vector class? ;-)

So all in all, this comes down to design tradeoffs by your Standard
Library vendor.. if you make the vector larger, with more objects, you
might observe more efficiency taking place immediately.

Btw. Just out of morbid curiosity, if your vector overflows.. which is
better, to double the size, or grow only 50%, or if something else,
what? I know the Dinkumware's (old) answer to this because this was
covered, I think in this same group some years ago, I recall P.Becker
(?) mentioned some rationale to explain the behaviour. I'm drifting
off-topic for your concerns but just popped to mind..

I hope this was any help..

Aug 30 '05 #19
Jon Slaughter wrote:


Yes, I see that now and if you would have said that in the first place we
could have saved each other a lot more time...


Everyone would have saved 'a lot more time' if you just would swallow down
your pride and *read* a book about C++.

What you are dealing with here is all pretty basic C++.

--
Karl Heinz Buchegger
kb******@gascad.at
Aug 30 '05 #20
Jon Slaughter wrote:
Output:

Object being created
Object being created
Object being removed
Object being removed


BTW, copying and pasting your code directly gives the output of(I did not
change a damn thing either).

Object being created
Object being created
Object being created
Object being removed
Object being removed
Object being removed


That's because a compiler is allowed to optimize away some
temporaries. Thats why Mike's compiler creates only 1 temporary
while your compiler sets up for 2 temporaries. You might want
to try to compile your code in 'release mode' (with full optimization)
and see if your compiler gets rid of an additional temporary also.

--
Karl Heinz Buchegger
kb******@gascad.at
Aug 30 '05 #21

"Karl Heinz Buchegger" <kb******@gascad.at> wrote in message
news:43***************@gascad.at...
Jon Slaughter wrote:
> Output:
>
> Object being created
> Object being created
> Object being removed
> Object being removed
>
BTW, copying and pasting your code directly gives the output of(I did not
change a damn thing either).

Object being created
Object being created
Object being created
Object being removed
Object being removed
Object being removed


That's because a compiler is allowed to optimize away some
temporaries. Thats why Mike's compiler creates only 1 temporary
while your compiler sets up for 2 temporaries. You might want
to try to compile your code in 'release mode' (with full optimization)
and see if your compiler gets rid of an additional temporary also.


tried that and same results... any other great suggestions?
--
Karl Heinz Buchegger
kb******@gascad.at

Aug 30 '05 #22

"Karl Heinz Buchegger" <kb******@gascad.at> wrote in message
news:43***************@gascad.at...
Jon Slaughter wrote:


Yes, I see that now and if you would have said that in the first place we
could have saved each other a lot more time...


Everyone would have saved 'a lot more time' if you just would swallow down
your pride and *read* a book about C++.

What you are dealing with here is all pretty basic C++.

--
Karl Heinz Buchegger
kb******@gascad.at


omg... wtf is up with this book shit? I thought this group was to get help?
maybe I am wrong? just a communion of arrogant assholes? fact is I have
read many books on C++ before and I used to program fairly fluently in it,
but this was over 10 years ago and I am trying to get back into it. I did
look on sgi's stl introduction page before I came here and the documentation
is pretty sorry.

Besides, you are pretty arrogant yourself because you say I need to swallow
my pride and read a book... thats kinda stupid. I came in here asking for
questions because I thought this was a place to get help(it used to be years
ago I suppose before it was taken over by the likes of you)... my fault for
assuming.

I got an idea!! how bout you go read a book asshole?
Aug 30 '05 #23
"Jon Slaughter" <Jo***********@Hotmail.com> schrieb:
That's because a compiler is allowed to optimize away some
temporaries. Thats why Mike's compiler creates only 1 temporary
while your compiler sets up for 2 temporaries. You might want to
try to compile your code in 'release mode' (with full
optimization) and see if your compiler gets rid of an additional
temporary also.


tried that and same results... any other great suggestions?


I'd like to mention the word "copy constructor".

T.M.
Aug 30 '05 #24

"persenaama" <ju***@liimatta.org> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
The explanation is probably very simple. std::vector is basicly
mimicking array semantics for memory storage, looks like a duck, sounds
like a duck.. walks like a duck, anyway..

yes, I assumed that because I have written my own vector and set container
classes before that are similar to the basic features of STL's but I have
yet to find any good documentation that describes that exact behavior of the
library in detail.

http://www.sgi.com/tech/stl/stl_introduction.html is pretty poor IMO and
thats all that I can seem to find.

When vector runs out of capacity, it is grown.. when vector is grown
new objects are being created, and existing ones are *copied* to the
new storage that is being allocated. It is not defined as far as I can
remember how large the capacity of a vector is initially, and I don't
remember liking to read Dinkumware's (whose implementation you are
currently using) code very much (sorry DW).
Well, I'm not so concerned with the inner workings of the vector library
except that it is not bloated. The copy procedure was just something that I
was not familiar with.. maybe I missed it when I was reading over the
basics. The whole point for me using the vector lib is mainly for automatic
memory allocation and deallocation for the expansion of the array and
possibly for future reasons that I am not aware of(as the automatic memory
allocation is not that big a deal to implement but all the algorithms that
go along with the class are(cause I rather not implement them myself)).

The small vectors rarely can both, efficient in runtime and memory
footprint. If they are runtime efficient then it means they need some
larger constant as initial capacity, which wastes memory and
vice-versa. In this context, how would you implement your Standard
Library's vector class? ;-)
I suppose this depends on the application. I am using a nested set of
classes each wrapping an STL vector and at most the will probably contain 15
elements each.

I don't think there is a direct relation between memory and speed(in this
case). In my case there is no reason to allocate any inital extra capacity
because the array is almost static for the majority of run time. i.e.,
there is a basicaly a setup procedure that will initalize the vector and
during the main loop of the program one will usually not mess with the
vector(well, its more complicated than that since I have several vectors...
most will not be modified most of the time(if that makes sense)).

So all in all, this comes down to design tradeoffs by your Standard
Library vendor.. if you make the vector larger, with more objects, you
might observe more efficiency taking place immediately.
depends on what you are using the vector for. Like I said, I the majority
of my vectors are basicaly static entities for the majory of the program and
have very little influence on performance. I am using STL's vector because
it is easy than writing my own and to be consistent with other parts of the
program that use STL and also for possible future design reasons.

Btw. Just out of morbid curiosity, if your vector overflows.. which is
better, to double the size, or grow only 50%, or if something else,
what? I know the Dinkumware's (old) answer to this because this was
covered, I think in this same group some years ago, I recall P.Becker
(?) mentioned some rationale to explain the behaviour. I'm drifting
off-topic for your concerns but just popped to mind..
Well, I would say it depends on context. In my specific case I have about 5
vectors that I am using and 3 of them will be static for most of the time,
one will be used like crazy(inserting, removing, manipulating,etc...) and
the other is about midway. I'm using STL's vector for all of them. I
suppose that as long as its optimized for the "like crazy" case then I'll be
fine. I just tend to have a problem wasting memory and performance for
absolutely no reason except lazyness.

When I did my own vector class I allowed the user to change how much extra
capacity one could allocate when an overflow occured... maybe real advanced
methods would have some optimizing feature on this parameter to find the
best number(ofcourse I doubt there is one but...).

I hope this was any help..


Well, not really... but...
Aug 30 '05 #25

"Jon Slaughter" <Jo***********@Hotmail.com> wrote in message
news:11*************@corp.supernews.com...

Well, for future reference why don't you just not reply to my messages?


OK, I won't. And thanks for letting me know that my attempts
to help you are a waste of time.

-Mike

Aug 30 '05 #26
"Jon Slaughter" <Jo***********@Hotmail.com> wrote in
news:11************@corp.supernews.com:

"Karl Heinz Buchegger" <kb******@gascad.at> wrote in message
news:43***************@gascad.at...
Jon Slaughter wrote:


Yes, I see that now and if you would have said that in the first
place we could have saved each other a lot more time...
Everyone would have saved 'a lot more time' if you just would swallow
down your pride and *read* a book about C++.

What you are dealing with here is all pretty basic C++.


omg... wtf is up with this book shit? I thought this group was to get
help? maybe I am wrong? just a communion of arrogant assholes? fact


Hmm.. an aversion to actually exerting yourself to learn something
instead of been spoon-fed everything? Funny that... _I_ prefer to teach
people who are actually wanting to learn, which many, many new/infrequent
posters seem to want to do.
is I have read many books on C++ before and I used to program fairly
fluently in it, but this was over 10 years ago and I am trying to get
back into it. I did look on sgi's stl introduction page before I came
here and the documentation is pretty sorry.
Over 10 years ago, C++ wasn't Standardized. IIRC it was still the ARM
that was the "gospel" on C++. Get some decent books. "The C++
Programming Language" (Stroustrup) and "The C++ Standard Library"
(Josuttis) are good places to start.
Besides, you are pretty arrogant yourself because you say I need to
swallow my pride and read a book... thats kinda stupid. I came in here
asking for questions because I thought this was a place to get help(it
used to be years ago I suppose before it was taken over by the likes
of you)... my fault for assuming.
This is a place to get help on Standard C++. You may get a hint or two
on what may be going wrong on certain platform and/or implementation-
specific things, and then pointed to a more appropriate forum for that
specific question. Such as what appears to be an optimization issue with
whatever compiler you're using. It has been pointed out that the
compiler is free to optimize away certain temporaries. If your compiler
doesn't, that's an issue with your compiler and you'd have to take that
up in a newsgroup dedicated to your compiler. Failing that, with the
compiler vendor.
I got an idea!! how bout you go read a book asshole?


Willing to bet he's probably read more pertinent books on C++ than you
have.....

Aug 30 '05 #27
On Tue, 30 Aug 2005 04:28:13 -0500, Jon Slaughter wrote:
depends on what you are using the vector for. Like I said, I the majority
of my vectors are basicaly static entities for the majory of the program and
have very little influence on performance. I am using STL's vector because
it is easy than writing my own and to be consistent with other parts of the
program that use STL and also for possible future design reasons.

Well, I would say it depends on context. In my specific case I have about 5
vectors that I am using and 3 of them will be static for most of the time,
one will be used like crazy(inserting, removing, manipulating,etc...) and
the other is about midway. I'm using S TL's vector for all of them. I
suppose that as long as its optimized for the "like crazy" case then
I'll be fine. I just tend to have a problem wasting memory and
performance for absolutely no reason except lazyness.

When I did my own vector class I allowed the user to change how much
extra capacity one could allocate when an overflow occured... maybe real
advanced methods would have some optimizing feature on this parameter to
find the best number(ofcourse I doubt there is one but...).


You might want to check out the STL list instead of vector. Especially for
the case where you're inserting and removing like crazy. I don't believe
it will exhibit the copy problem, and insertions and removals are speedier
(no need to copy chunks of the vector around to open and close space).

You'll have to balance that with the need for random access. (In other
words, if you always walk your arrays from start to end, a list would be
ok. But if you need to access random elements of it, a vector is faster
for that part.)

- Jay

Aug 30 '05 #28
Jon Slaughter wrote:
I got an idea!! how bout you go read a book asshole?


You think this is the way to get people to help you?
*plonk*


Brian
Aug 30 '05 #29

"Jay Nabonne" <ja*********@sonicNOSPAM.com> wrote in message
news:pa****************************@sonicNOSPAM.co m...
On Tue, 30 Aug 2005 04:28:13 -0500, Jon Slaughter wrote:
depends on what you are using the vector for. Like I said, I the
majority
of my vectors are basicaly static entities for the majory of the program
and
have very little influence on performance. I am using STL's vector
because
it is easy than writing my own and to be consistent with other parts of
the
program that use STL and also for possible future design reasons.

Well, I would say it depends on context. In my specific case I have
about 5
vectors that I am using and 3 of them will be static for most of the
time,
one will be used like crazy(inserting, removing, manipulating,etc...) and
the other is about midway. I'm using S TL's vector for all of them. I
suppose that as long as its optimized for the "like crazy" case then
I'll be fine. I just tend to have a problem wasting memory and
performance for absolutely no reason except lazyness.

When I did my own vector class I allowed the user to change how much
extra capacity one could allocate when an overflow occured... maybe real
advanced methods would have some optimizing feature on this parameter to
find the best number(ofcourse I doubt there is one but...).

You might want to check out the STL list instead of vector. Especially for
the case where you're inserting and removing like crazy. I don't believe
it will exhibit the copy problem, and insertions and removals are speedier
(no need to copy chunks of the vector around to open and close space).


I did check out the list and thought about using it and actually changed it
back to vector for some reason. The list does have constant amortized
insertion and removal at begining, middle, and end but I think the main
problem was that I think I wanted to treat it as an array and I couldn't
really easily do that with the list. I'm not sure though, I might change it
later. I'm new to STL and don't know all the details about the different
containers and it might turn out that there is not really any performance
issues in my case using either one(but thats main thing I'm afraid of... if
it works find with vectors doing what I need to do then will turn the part I
need into a list and see what happens).

You'll have to balance that with the need for random access. (In other
words, if you always walk your arrays from start to end, a list would be
ok. But if you need to access random elements of it, a vector is faster
for that part.)
yeah, thats why I used the vector in the first place. If my application
performs well with the vector class I might try using a list and give it an
array like structure(which might make the list to bulky in the long run
though).

- Jay


Jon
Aug 30 '05 #30

"Default User" <de***********@yahoo.com> wrote in message
news:3n************@individual.net...
Jon Slaughter wrote:
I got an idea!! how bout you go read a book asshole?
You think this is the way to get people to help you?


Help?? is that what you call it? I don't need that kinda "help". If you
think that if you are going to help someone that also gives you the right to
treat them as stupid then you have a strange version of help... a version I
don't want. Took mike like 6 posts to say the exact problem that is only
about 3 lines instead of all the bullshit he did trying to show his ego.


*plonk*


Brian

Aug 30 '05 #31

"Andre Kostur" <nn******@kostur.net> wrote in message
news:Xn*******************************@207.35.177. 134...
"Jon Slaughter" <Jo***********@Hotmail.com> wrote in
news:11************@corp.supernews.com:

"Karl Heinz Buchegger" <kb******@gascad.at> wrote in message
news:43***************@gascad.at...
Jon Slaughter wrote:
Yes, I see that now and if you would have said that in the first
place we could have saved each other a lot more time...

Everyone would have saved 'a lot more time' if you just would swallow
down your pride and *read* a book about C++.

What you are dealing with here is all pretty basic C++.


omg... wtf is up with this book shit? I thought this group was to get
help? maybe I am wrong? just a communion of arrogant assholes? fact


Hmm.. an aversion to actually exerting yourself to learn something
instead of been spoon-fed everything? Funny that... _I_ prefer to teach
people who are actually wanting to learn, which many, many new/infrequent
posters seem to want to do.


spoon feed? you gotta be kidding? I've never seen so much egotism in one
sitting at the computer ever in my life. I've asked 3 questions in this
newgroup refering to STL(because of the shitty documentation) and you say
I'm being spoon fed? grow up! I guess I'm only allowed 1 post a year or
else I'm trying to be spoon fed? whats the exact number?
I GOT AN IDEA!!! IF YOU DON'T WANT TO HELP THEN SHUTUP AND DON'T!!!?!?!?!?!
Got damn that is a very simple fucking principle that seems to exscape some
of the most brilliant minds in the world(i.e. this NG).

It seems to me that the only reason some of you post is because you just
need to get your ego up a little more for some reason.

If you think I should go read a book then the response should be something
like

"STL is a complex and intricate language that is difficult to explain in
detail without writing a book, hence you might save some time and learn more
from reading these good books: XXX, YYY, ZZZ."

instead of

"Go read a book you dumbass cause your an idiot and lazy!"(which is
essentially what several of you are saying(well, one and others just hopped
on to join the fun(like kids))).

Fact is maybe I do need a book... how bout you buy it for me? how bout you
let me borrow all the books you have(cause I know you have a lot)? How bout
you be polite about it and also use a little NG etiquette? To hard to ask?
Have a bad day at the office? Wife left ya? Lost house in Kitrina? Mugged??

I GOT AN IDEA!!! IF YOU DON'T WANT TO HELP THEN SHUTUP AND DON'T!!!?!?!?!?!
Anyways, I've wasted to much time replying... just a waste anyways.
Aug 30 '05 #32
"Jon Slaughter" <Jo***********@Hotmail.com> wrote in
news:11*************@corp.supernews.com:
I did check out the list and thought about using it and actually
changed it back to vector for some reason. The list does have
constant amortized insertion and removal at begining, middle, and end
Yep... list's good for that...
but I think the main problem was that I think I wanted to treat it as
an array and I couldn't really easily do that with the list. I'm not
True. No indexing on a list, and it's not stored contiguously (at least,
not necessarily....)
sure though, I might change it later. I'm new to STL and don't know
all the details about the different containers and it might turn out
that there is not really any performance issues in my case using
either one(but thats main thing I'm afraid of... if it works find with
vectors doing what I need to do then will turn the part I need into a
list and see what happens).


I'd recommend picking up a copy of Effective STL by Scott Meyers.
You'll have to balance that with the need for random access. (In
other words, if you always walk your arrays from start to end, a list
would be ok. But if you need to access random elements of it, a
vector is faster for that part.)


yeah, thats why I used the vector in the first place. If my
application performs well with the vector class I might try using a
list and give it an array like structure(which might make the list to
bulky in the long run though).


If you want random access, you may want to look up std::deque as well....
but it's not good for insertions/deletions in the middle...
Aug 30 '05 #33
Jay Nabonne <ja*********@sonicNOSPAM.com> schrieb:
You might want to check out the STL list instead of vector.


No, his problem is absolutely independent from the container type.
It's not even dependent on STL. It's simple C++.

T.M.
Aug 31 '05 #34
Ram
Jon Slaughter wrote:
I'm having a problem allocating some elements of a vector then deleting
them.

Basicaly I have something like this:
class base
{
private:
std::vector<object> V;
//std::vector<*object> V;

public:

void addObject()
{
object *temp = new object;
V.push_back(*temp);

//V.push_back(new object);
}
It seems, you haven't read any good C++ book. Whenever you push
something on a vector, it creates a copy for itself. So the vector
doesn't contain the object which you _just created_ rather a copy of
it. After coming out of this function there's no way you can get hold
of the newly created object. Memory leak..

Instead you can just say

V.push_back(object());


void removeObject(index)
{
delete &V[index];
V.erase(V.begin() + index);

//delete V[index];
//V.erase(V.begin() + index);
}
delete &V[index]; // calls dtor
V.erase(V.begin() + index); // calls dtor again

Each object in the vector gets destroyed automatically when you
erase/clear it.There is no need for explicit delete call for each
element.

delete V[index];

is okay if the vector contains pointers to dynamically created objects
which need to be cleaned up. But note that it frees up the object
pointed by elements in vector and not the vector element itself,
there's no need to do that anyway..
};

the commented line is where I used the pointerized version. In the first
case the object's destructor gets called twice(I suppose because when I call
addObject the local variable goes out of scope(any way to prevent this) and
in the second case it doesn't get called at all ;/

I'd rather not use a vector of pointers though... I thought maybe I could
declare the object *temp as static but this seems to be kinda a hack... I
just need a way to say "don't call the destructor for this local object when
it goes out of scope" or something.

Any ideas?


Create a temporary local object (dynamically created objects are not
local) and push it on the vector. Don't call delete when you need to
remove them, simply erase will do.

HTH
Ram

Aug 31 '05 #35
Torsten Mueller wrote:

Jay Nabonne <ja*********@sonicNOSPAM.com> schrieb:
You might want to check out the STL list instead of vector.


No, his problem is absolutely independent from the container type.
It's not even dependent on STL. It's simple C++.


He. he. A smart pointer could solve his 'problems'. But
then again I fear that he is telling us, that we don't need
to tell him, because he is the greates programmer in the world
and has used smart pointers before we were born and nobody
is going to help him with that information and ....
--
Karl Heinz Buchegger
kb******@gascad.at
Aug 31 '05 #36

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Dave | last post: by
1 post views Thread by Nimmi Srivastav | last post: by
3 posts views Thread by Nimmi Srivastav | last post: by
1 post views Thread by Douglas Peterson | last post: by
2 posts views Thread by Dave | last post: by
3 posts views Thread by silver360 | last post: by
9 posts views Thread by rohits123 | last post: by
10 posts views Thread by jeffjohnson_alpha | last post: by
15 posts views Thread by LuB | last post: by
29 posts views Thread by =?Utf-8?B?R2Vvcmdl?= | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.