473,714 Members | 2,264 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

copying a vector of objects at runtime

Hi,
I have a vector defined like this:
std::vector<Loa d*LoadList;
which is populated with different objects of classes that are derived from
'Load'.
I need to make a copy of this list during runtime.
I imagine I'd have to loop through the list, make a copy of each of the
objects in the vector using the copy constructor... but I don't know the
class name during run time so that I can call the appropriate copy
constructor.
actually, I read up on 'typeid' which I supposed would give me the class
name... but I am still confused as how I can call the appropriate copy
constructor for that class during run time.
One option would be to do a string compare of the class names... but that
requires for me to be aware of all the classes derived from 'Load'.
Is there some other way to go about this?
thanks,
Julian.
Jul 10 '08 #1
9 1732

"Julian" <ju****@nospamt amu.eduwrote in message
news:g5******** **@news.tamu.ed u...
Hi,
I have a vector defined like this:
std::vector<Loa d*LoadList;
which is populated with different objects of classes that are derived from
'Load'.
I need to make a copy of this list during runtime.
I imagine I'd have to loop through the list, make a copy of each of the
objects in the vector using the copy constructor... but I don't know the
class name during run time so that I can call the appropriate copy
constructor.
actually, I read up on 'typeid' which I supposed would give me the class
name... but I am still confused as how I can call the appropriate copy
constructor for that class during run time.
One option would be to do a string compare of the class names... but that
requires for me to be aware of all the classes derived from 'Load'.
Is there some other way to go about this?
thanks,
Julian.
I did some more searching and looks like I found the solution from a 10 yr
old post!
http://groups.google.com/group/comp....jects+c%2B%2B#
do let me know if this isn't the right solution
sorry for the inconvenience
Jul 10 '08 #2
"Julian" <ju****@nospamt amu.eduwrote in
news:g5******** **@news.tamu.ed u:
Hi,
I have a vector defined like this:
std::vector<Loa d*LoadList;
which is populated with different objects of classes that are derived
from 'Load'.
I need to make a copy of this list during runtime.
I imagine I'd have to loop through the list, make a copy of each of
the objects in the vector using the copy constructor... but I don't
know the class name during run time so that I can call the appropriate
copy constructor.
Hmmm, if copying the objects in the vector is the answer, then I have to
wonder why there are pointers in the vector to begin with. That is,
wouldn't vector<Loadhave been a better place to start? Then copying
would be as simple as LoadList2 = LoadList. IME the only time you
really want a vector of pointers is if the objects have identity
(can't/shouldn't be copied at all) or are horrendously expensive to
copy.

If you still want to copy the vector of pointers (after considering
making them value types instead), you can do something like:

#include <iostream>
#include <sstream>
#include <vector>

template <typename T>
T * clone(T * a)
{
return new T(*a); //assuming copy constructor
}

template <typename T>
class clone_insert_it erator : public std::iterator
<std::output_it erator_tag, typename T::value_type>
{
T& m_Container;
public:
explicit clone_insert_it erator(T & container) : m_Container
(container) {}
clone_insert_it erator<T& operator=(typen ame T::value_type const &
a)
{
m_Container.pus h_back(clone(a) );
return *this;
}
clone_insert_it erator<T& operator*()
{
return *this;
}
clone_insert_it erator<T& operator++()
{
return *this;
}
clone_insert_it erator<Toperato r++(int)
{
return *this;
}
};
int main()
{
std::vector<int *v;
std::vector<int *v1;

v.push_back(new int(5));
v.push_back(new int(1));
v.push_back(new int(10));
v.push_back(new int(7));

clone_insert_it erator<std::vec tor<int * cii(v1);
std::copy(v.beg in(), v.end(), cii);

for (int ix = 0; ix < v1.size(); ++ix)
{
std::cout << *v[ix] << std::endl;
}
std::cout << std::endl;
std::cout << std::endl;
for (int ix = 0; ix < v1.size(); ++ix)
{
std::cout << *v1[ix] << std::endl;
}
}
Which seems to work, but I made no attempt at robustness nor
completeness for any particular use.
joe
Jul 10 '08 #3
"Julian" <ju****@nospamt amu.eduwrote:
"Julian" <ju****@nospamt amu.eduwrote:
I have a vector defined like this:
std::vector<Loa d*LoadList;
which is populated with different objects of classes that are derived from
'Load'.
I need to make a copy of this list during runtime.
I imagine I'd have to loop through the list, make a copy of each of the
objects in the vector using the copy constructor... but I don't know the
class name during run time so that I can call the appropriate copy
constructor.
actually, I read up on 'typeid' which I supposed would give me the class
name... but I am still confused as how I can call the appropriate copy
constructor for that class during run time.
One option would be to do a string compare of the class names... but that
requires for me to be aware of all the classes derived from 'Load'.
Is there some other way to go about this?
thanks,
Julian.

I did some more searching and looks like I found the solution from a 10 yr
old post!
http://groups.google.com/group/comp....d/1d4181588643
35d0/ea75e39ab5004cf c?lnk=st&q=copy ing+objects+c%2 B%2B#
do let me know if this isn't the right solution
sorry for the inconvenience
Yes, this is an FAQ:

http://www.parashift.com/c++-faq-lit....html#faq-20.8

Be advised though, this may not be the best solution for you. You should
also look into holding a vector of smart pointers. If that will work for
you (i.e., if it's ok if both vectors actually point to the same set of
objects,) then copying will be a simple matter of assignment:

vector<smart_pt r<Load loadList;
vector<smart_pt r<Load copy = loadList;
Jul 11 '08 #4
On Jul 10, 9:46*pm, "Daniel T." <danie...@earth link.netwrote:
"Julian" <jul...@nospamt amu.eduwrote:
"Julian" <jul...@nospamt amu.eduwrote:
I have avectordefined like this:
std::vector<Loa d*LoadList;
which is populated with differentobject sof classes that are derived from
'Load'.
I need to make a copy of this list during runtime.
I imagine I'd have to loop through the list, make a copy of each of the
>objectsin thevectorusing the copy constructor... but I don't know the
class name during run time so that I can call the appropriate copy
constructor.
actually, I read up on 'typeid' which I supposed would give me the class
name... but I am still confused as how I can call the appropriate copy
constructor for that class during run time.
One option would be to do a string compare of the class names... but that
requires for me to be aware of all the classes derived from 'Load'.
Is there some other way to go about this?
thanks,
Julian.
I did some more searching and looks like I found the solution from a 10yr
old post!
http://groups.google.com/group/comp....ead/thread/1d4...
35d0/ea75e39ab5004cf c?lnk=st&q=copy ing+objects+c%2 B%2B#
do let me know if this isn't the right solution
sorry for the inconvenience

Yes, this is an FAQ:

http://www.parashift.com/c++-faq-lit....html#faq-20.8

Be advised though, this may not be the best solution for you. You should
also look into holding avectorof smart pointers. If that will work for
you (i.e., if it's ok if both vectors actually point to the same set ofobjects,) thencopyingwill be a simple matter of assignment:

vector<smart_pt r<Load loadList;vector <smart_ptr<Lo ad copy = loadList;
thanks for the response...I will look into smart pointers. but in this
case, I actually want to create a copy of the set of objects. not just
a set of pointers that point to the original set of objects.
I am trying to parallelize some of the steps in my Finite element
analysis program and the reasoning for doing this is so that each
processor can have its own set of objects so that it doesn't cause
conflicts with what the other processor is doing. hope that makes
sense.

Julian.
Jul 11 '08 #5
On Jul 10, 11:35*pm, spacemanspiff <jul...@gmail.c omwrote:
On Jul 10, 9:46*pm, "Daniel T." <danie...@earth link.netwrote:
"Julian" <jul...@nospamt amu.eduwrote:
"Julian" <jul...@nospamt amu.eduwrote:
I have avectordefined like this:
std::vector<Loa d*LoadList;
which is populated with differentobject sof classes that are derivedfrom
'Load'.
I need to make a copy of this list during runtime.
I imagine I'd have to loop through the list, make a copy of each ofthe
objectsin thevectorusing the copy constructor... but I don't know the
class name during run time so that I can call the appropriate copy
constructor.
actually, I read up on 'typeid' which I supposed would give me the class
name... but I am still confused as how I can call the appropriate copy
constructor for that class during run time.
One option would be to do a string compare of the class names... but that
requires for me to be aware of all the classes derived from 'Load'.
Is there some other way to go about this?
thanks,
Julian.
I did some more searching and looks like I found the solution from a 10 yr
old post!
>http://groups.google.com/group/comp....ead/thread/1d4....
35d0/ea75e39ab5004cf c?lnk=st&q=copy ing+objects+c%2 B%2B#
do let me know if this isn't the right solution
sorry for the inconvenience
Yes, this is an FAQ:
http://www.parashift.com/c++-faq-lit....html#faq-20.8
Be advised though, this may not be the best solution for you. You should
also look into holding avectorof smart pointers. If that will work for
you (i.e., if it's ok if both vectors actually point to the same set ofobjects,) thencopyingwill be a simple matter of assignment:
vector<smart_pt r<Load loadList;vector <smart_ptr<Lo ad copy = loadList;

thanks for the response...I will look into smart pointers. but in this
case, I actually want to create a copy of the set of objects. not just
a set of pointers that point to the original set of objects.
I am trying to parallelize some of the steps in my Finite element
analysis program and the reasoning for doing this is so that each
processor can have its own set of objects so that it doesn't cause
conflicts with what the other processor is doing. hope that makes
sense.

Julian.
Sorry for the confusion... i am the original poster. I just started
using Google groups now
Jul 11 '08 #6
On Jul 10, 10:02*am, Joe Greer <jgr...@doublet ake.comwrote:
"Julian" <jul...@nospamt amu.eduwrote innews:g5****** ****@news.tamu. edu:
Hi,
I have a vector defined like this:
std::vector<Loa d*LoadList;
which is populated with different objects of classes that are derived
from 'Load'.
I need to make a copy of this list during runtime.
I imagine I'd have to loop through the list, make a copy of each of
the objects in the vector using the copy constructor... but I don't
know the class name during run time so that I can call the appropriate
copy constructor.

Hmmm, if copying the objects in the vector is the answer, then I have to
wonder why there are pointers in the vector to begin with. *That is,
wouldn't vector<Loadhave been a better place to start? *Then copying
would be as simple as LoadList2 = LoadList. *IME the only time you
really want a vector of pointers is if the objects have identity
(can't/shouldn't be copied at all) or are horrendously expensive to
copy.
I'm not really sure if I understand the first part of your response.
from what I understand (and please let me know if i'm on the wrong
track), vector<Loadcan only store only Load objects. even if i try
to store an object of a class derived from Load, it still stores only
a Load object because it calls Load(const Load&) when you do a
push_back.
In my case, I want this vector to 'store' a combination of Load
objects AND other objects that are derived from Load.
hope this helps in describing my situation... and please let me know
if it better for me to use some other c++ strategy.
thanks,
Julian.
Jul 11 '08 #7
Joe Greer wrote:
"Julian" <ju****@nospamt amu.eduwrote in
news:g5******** **@news.tamu.ed u:
>Hi,
I have a vector defined like this:
std::vector<Lo ad*LoadList;
which is populated with different objects of classes that are derived
from 'Load'.
I need to make a copy of this list during runtime.
I imagine I'd have to loop through the list, make a copy of each of
the objects in the vector using the copy constructor... but I don't
know the class name during run time so that I can call the appropriate
copy constructor.

Hmmm, if copying the objects in the vector is the answer, then I have to
wonder why there are pointers in the vector to begin with. That is,
wouldn't vector<Loadhave been a better place to start? Then copying
would be as simple as LoadList2 = LoadList. IME the only time you
really want a vector of pointers is if the objects have identity
(can't/shouldn't be copied at all) or are horrendously expensive to
copy.
You forgot the other case, where your vector contains polymorphic
objects. But then you should probably be using a container of your
favorite smart pointer.
Jul 11 '08 #8
Julian <ju****@gmail.c omwrote in
news:00******** *************** ***********@59g 2000hsb.googleg roups.com:
On Jul 10, 10:02*am, Joe Greer <jgr...@doublet ake.comwrote:
>"Julian" <jul...@nospamt amu.eduwrote
innews:g5***** *****@news.tamu .edu:

I'm not really sure if I understand the first part of your response.
from what I understand (and please let me know if i'm on the wrong
track), vector<Loadcan only store only Load objects. even if i try
to store an object of a class derived from Load, it still stores only
a Load object because it calls Load(const Load&) when you do a
push_back.
In my case, I want this vector to 'store' a combination of Load
objects AND other objects that are derived from Load.
hope this helps in describing my situation... and please let me know
if it better for me to use some other c++ strategy.
thanks,
Julian.
Ah yes, I forgot polymorphism... In that case, if your objects have
identity, that is, you really only want one instance of it, then you might
look at a smart_ptr (from either TR1 or boost) to manage lifetime of the
object and just copy the vector normally. Or you make your Load interface
contain a clone() method of some sort which has the object create a copy of
itself. A clone_inserter iterator can then be made which invokes this
method to get the clone of the object and use std::copy() as I described
elsewhere.

joe
Jul 11 '08 #9
red floyd <no**********@e xample.comwrote in
news:qi******** **********@nlpi 064.nbdc.sbc.co m:
Joe Greer wrote:
>"Julian" <ju****@nospamt amu.eduwrote in
news:g5******* ***@news.tamu.e du:
>>Hi,
I have a vector defined like this:
std::vector<L oad*LoadList;
which is populated with different objects of classes that are
derived from 'Load'.
I need to make a copy of this list during runtime.
I imagine I'd have to loop through the list, make a copy of each of
the objects in the vector using the copy constructor... but I don't
know the class name during run time so that I can call the
appropriate copy constructor.

Hmmm, if copying the objects in the vector is the answer, then I have
to wonder why there are pointers in the vector to begin with. That
is, wouldn't vector<Loadhave been a better place to start? Then
copying would be as simple as LoadList2 = LoadList. IME the only
time you really want a vector of pointers is if the objects have
identity (can't/shouldn't be copied at all) or are horrendously
expensive to copy.

You forgot the other case, where your vector contains polymorphic
objects. But then you should probably be using a container of your
favorite smart pointer.
Yep. Somehow, the way the question was worded, It didn't occur to me that
these were pointers to a base/interface. Sigh.

joe
Jul 11 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3649
by: Robert Tarantino | last post by:
Hello, I am trying to find a way to create a scheduled task or service that will copy my local profile folders under "Documents and settings" to a network drive. This would allow me to restore my settings if my profile became tampered with or corrupt. Is there any sample code available out there? -Robert
20
12985
by: Hanzo | last post by:
I'm iterating over a vector of base class pointers and deleting those which meet a certain criteria...i'm using pretty text-book code for the particular delete/erasure (it's straight out of Myers' Effective STL), and reads like this: void CGame::RemoveDeadObjects() { // cleanup crew!! vector<CDrawableObject*>::iterator i;
7
10627
by: Forecast | last post by:
I run the following code in UNIX compiled by g++ 3.3.2 successfully. : // proj2.cc: returns a dynamic vector and prints out at main~~ : // : #include <iostream> : #include <vector> : : using namespace std; : : vector<string>* getTyphoon()
11
8874
by: Steve | last post by:
Hi, I'm using a std::vector to store a list of user defined objects. The vector may have well over 1000 elements, and I'm suffering a performance hit. If I use push_back I get a much worse perfomance than if I first define the vector of a given size, then write to the elements with myvec = However, I'm currently thinking that it isn't feasible to obtain the vector size, so really need to resize the vector dynamically as I go. Is...
6
5310
by: Andreas Bauer | last post by:
I've got an array in the vein of MyType* array; arry = new MyType; This of course works fine, but I have the need to dynamically grow the boundaries of that array at runtime. I can't seem to use std :: vector or any other container, cause I've got two more "lists" which keep pointers to the elements of `array'.
8
1949
by: Hagen | last post by:
Hi, I have a question that you probably shouldn´t worry about since the compiler cares for it, but anyways: When you run your compiler with optimization turned on (eg. g++ with -Ox flag) and your program gets significantly faster than without, did you write bad code/ have a bad design? Cause what happens in those optimization steps is, I think, mostly
6
2562
by: solex | last post by:
Hello, I am trying to use serialization to copy objects. The object in question "Institution" inherits from a parent object "Party" both are marked as <Serializable()>. Initially I can copy an empty Institution to another empty Institution, using the following routine: Private Sub CopyObject(ByRef FromObject As Object, ByRef ToObject As Object) Dim m As New MemoryStream Dim b As New BinaryFormatter
8
18578
by: Manuel | last post by:
Hi! If I've a vector filled with abstract classes, can I push in it the derived classes too? Even if derived classes have new methods? I've done some experiments, and it seem I can push the derived classes, but I can use them only calling the methods declared in abstract class (the new methods declared only in derived classes return an error). Please take a look to my code (hey, this is not an homework!
9
3754
by: Jess | last post by:
Hello, I tried to clear a vector "v" using "v.clear()". If "v" contains those objects that are non-built-in (e.g. string), then "clear()" can indeed remove all contents. However, if "v" contains built-in types (e.g. int), then "clear()" doesn't remove anything at all. Why does "clear()" have this behaviour? Also, when I copy one vector "v1" from another vector "v2", with "v1" longer than "v2" (e.g. "v1" has 2 elements and "v2" has...
0
8712
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9177
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9077
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9021
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6637
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5951
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4727
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3159
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2524
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.