473,769 Members | 2,359 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

simple question about containers

I was wondering if there is a container (i.e. a vector) that can hold
data structures of differing sizes. I was thinking of something along
the lines of a container of classes. Think of a backpack you can take
items from and put items into of different sizes.

The reason I want to know is I am about to try my hands at learning
classes and need to do it in a way I can grasp - ala gaming concepts
(see inventory example above.)

Thanks in advance.
May 24 '07 #1
8 1281
Devon Null wrote:
I was wondering if there is a container (i.e. a vector) that can hold
data structures of differing sizes. I was thinking of something along
the lines of a container of classes. Think of a backpack you can take
items from and put items into of different sizes.

The reason I want to know is I am about to try my hands at learning
classes and need to do it in a way I can grasp - ala gaming concepts
(see inventory example above.)
Hold smart pointers to your 'data structures of differing sizes'
inside the container (e.g. vector) and the problem disappears.

HTH,
- J.
May 24 '07 #2
Devon Null <th************ *@gmail.comwrot e:
I was wondering if there is a container (i.e. a vector) that can hold
data structures of differing sizes. I was thinking of something along
the lines of a container of classes. Think of a backpack you can take
items from and put items into of different sizes.
Not directly: the standard containers must have homogeneous contents.
However, one technique around this is if all the items derive from a
common base class, then you can store base-pointers in the container, at
which point the base-pointers can point to the derived objects.
However, this introduce lifetime management issues. Smart pointers can
help in that situation (but not std::auto_ptr, which does not fulfill
the container requirements). Some libraries also have their own version
of a pointer_vector or whatever.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
May 24 '07 #3
On May 24, 12:30 pm, Devon Null <theronnights.. .@gmail.comwrot e:
I was wondering if there is a container (i.e. a vector) that can hold
data structures of differing sizes. I was thinking of something along
the lines of a container of classes. Think of a backpack you can take
items from and put items into of different sizes.

The reason I want to know is I am about to try my hands at learning
classes and need to do it in a way I can grasp - ala gaming concepts
(see inventory example above.)

Thanks in advance.

The backpack isn't storing the specifications of each item.
It simply stores objects, not classes.
It can also store base pointers to derived entities (which is what you
are looking for).
Assuming you have some form of inheritance hierarchy:

class Item {
virtual ~Item() = 0;
};

Item::~Item() { }

class Weapon : public Item { };

class Potion : public Item { };

int main()
{
// Item item; // error, Item is abstract
Weapon weapon;
Potion potion;
std::vector< Base* inventory;
inventory.push_ back( &weapon );
inventory.push_ back( &potion );
}

I'ld suggest keeping the base class abstract.
Types Weapon and Potion have their own specific attributes and their
own specific member functions.

Once you are comfortable with such a scenario, do look into smart
pointers (ie: boost:shared_pt r).
Otherwise, you'll need to manage the lifetime of those Items.
May 24 '07 #4
On May 24, 12:30 pm, Devon Null <theronnights.. .@gmail.comwrot e:
I was wondering if there is a container (i.e. a vector) that can hold
data structures of differing sizes. I was thinking of something along
the lines of a container of classes. Think of a backpack you can take
items from and put items into of different sizes.

The reason I want to know is I am about to try my hands at learning
classes and need to do it in a way I can grasp - ala gaming concepts
(see inventory example above.)

Thanks in advance.

The backpack isn't storing the specifications of each item.
It simply stores objects, not classes.
It can also store base pointers to derived entities (which is what you
are looking for).
Assuming you have some form of inheritance hierarchy:

class Item {
virtual ~Item() = 0;

};

Item::~Item() { }

class Weapon : public Item { };

class Potion : public Item { };

int main()
{
// Item item; // error, Item is abstract
Weapon weapon;
Potion potion;
std::vector< Item* inventory;
inventory.push_ back( &weapon );
inventory.push_ back( &potion );

}

I'ld suggest keeping the base class abstract.
Types Weapon and Potion have their own specific attributes and their
own specific member functions.

Once you are comfortable with such a scenario, do look into smart
pointers (ie: boost:shared_pt r).
Otherwise, you'll need to manage the lifetime of those Items.
May 24 '07 #5
Salt_Peter wrote:
On May 24, 12:30 pm, Devon Null <theronnights.. .@gmail.comwrot e:
>I was wondering if there is a container (i.e. a vector) that can hold
data structures of differing sizes. I was thinking of something along
the lines of a container of classes. Think of a backpack you can take
items from and put items into of different sizes.

The reason I want to know is I am about to try my hands at learning
classes and need to do it in a way I can grasp - ala gaming concepts
(see inventory example above.)

Thanks in advance.


The backpack isn't storing the specifications of each item.
It simply stores objects, not classes.
It can also store base pointers to derived entities (which is what you
are looking for).
Assuming you have some form of inheritance hierarchy:

class Item {
virtual ~Item() = 0;
};

Item::~Item() { }

class Weapon : public Item { };

class Potion : public Item { };

int main()
{
// Item item; // error, Item is abstract
Weapon weapon;
Potion potion;
std::vector< Base* inventory;
inventory.push_ back( &weapon );
inventory.push_ back( &potion );
}

I'ld suggest keeping the base class abstract.
Types Weapon and Potion have their own specific attributes and their
own specific member functions.

Once you are comfortable with such a scenario, do look into smart
pointers (ie: boost:shared_pt r).
Otherwise, you'll need to manage the lifetime of those Items.

Took me a second but I think I see what is going on here with the base
class. I can see where that could be a nightmare in maintenance.I
grabbed a couple of .h files from http://ootips.org/yonat/4dev/ that
should help.

Another question - say I was to use this example, would my class
declarations go inside the braces in the statement

class Weapon : public Item { /*in here?*/ }; ?

Like I said, I am actually just about to jump into classes. I also
assume that I would do that for any class inheriting the public parts of
class Item (i.e. any items).
May 24 '07 #6
On May 24, 1:48 pm, Devon Null <theronnights.. .@xgmailx.comwr ote:
Salt_Peter wrote:
On May 24, 12:30 pm, Devon Null <theronnights.. .@gmail.comwrot e:
I was wondering if there is a container (i.e. a vector) that can hold
data structures of differing sizes. I was thinking of something along
the lines of a container of classes. Think of a backpack you can take
items from and put items into of different sizes.
The reason I want to know is I am about to try my hands at learning
classes and need to do it in a way I can grasp - ala gaming concepts
(see inventory example above.)
Thanks in advance.
The backpack isn't storing the specifications of each item.
It simply stores objects, not classes.
It can also store base pointers to derived entities (which is what you
are looking for).
Assuming you have some form of inheritance hierarchy:
class Item {
virtual ~Item() = 0;
};
Item::~Item() { }
class Weapon : public Item { };
class Potion : public Item { };
int main()
{
// Item item; // error, Item is abstract
Weapon weapon;
Potion potion;
std::vector< Base* inventory;
inventory.push_ back( &weapon );
inventory.push_ back( &potion );
}
I'ld suggest keeping the base class abstract.
Types Weapon and Potion have their own specific attributes and their
own specific member functions.
Once you are comfortable with such a scenario, do look into smart
pointers (ie: boost:shared_pt r).
Otherwise, you'll need to manage the lifetime of those Items.

Took me a second but I think I see what is going on here with the base
class. I can see where that could be a nightmare in maintenance.I
grabbed a couple of .h files fromhttp://ootips.org/yonat/4dev/that
should help.
Consider using boost's shared_ptr instead
>
Another question - say I was to use this example, would my class
declarations go inside the braces in the statement

class Weapon : public Item { /*in here?*/ }; ?
yes, keep in mind that different parts of your hierarchy will have
their own attributes and responsabilitie s. Example: an AssaultRifle
is_a type of Weapon which is_a type of Item.
>
Like I said, I am actually just about to jump into classes. I also
assume that I would do that for any class inheriting the public parts of
class Item (i.e. any items).
Not really. Consider that all items have a weight/mass. Item's
derivatives need not handle that aspect so you'ld keep weight in Item,
no virtual getweight() function needed. Weapon might itself become a
base class for concrete weapons (ie, rifle, laser, grenade, etc). All
weapons can fire() but each weapon fires in its own way. A rifle might
have an ammo count. And so on. See if the code below clarifies some
issues, i'm completely ignoring the fact that an Item needs to be
loaded/equipped.

Note how lifetimes are greatly simplified by the use of
boost::shared_p tr.

#include <iostream>
#include <vector>
#include <string>
#include <boost/shared_ptr.hpp>

class Item {
double weight;
protected:
Item(double w = 0.0) : weight(w) { }
public:
~Item() { std::cout << "~Item()\n" ; }
double getweight() const { return weight; }
virtual void use() = 0;
};

class Weapon : public Item
{
protected:
Weapon(double w = 0.0) : Item(w) { }
virtual void fire() = 0;
};

class AssaultRifle : public Weapon
{
int ammo;
public:
AssaultRifle(in t a = 16) : Weapon(20.1), ammo(a)
{
std::cout << "AssaultRifle() \n";
}
~AssaultRifle() { std::cout << "~AssaultRifle( )\n"; }
void use()
{
fire();
std::cout << "fired!, ammo left :" << ammo;
std::cout << std::endl;
}
private:
void fire() { --ammo; }
};

int main()
{
typedef boost::shared_p tr< Item SPtrItem;
std::vector< SPtrItem inventory;
inventory.push_ back( SPtrItem( new AssaultRifle(32 ) ) );

std::cout << "inventory[0]'s weight is: ";
std::cout << inventory.at(0)->getweight();
std::cout << std::endl;

inventory.at(0)->use(); // universal Item user
}

/*
AssaultRifle()
inventory[0]'s weight is: 20.1
fired!, ammo left :31
~AssaultRifle()
~Item()
*/

May 24 '07 #7
On May 24, 6:30 pm, Devon Null <theronnights.. .@gmail.comwrot e:
I was wondering if there is a container (i.e. a vector) that can hold
data structures of differing sizes. I was thinking of something along
the lines of a container of classes. Think of a backpack you can take
items from and put items into of different sizes.
The obvious answer is std::vector< boost::any >. Whether it is
the right answer will depend on your particular circumstances;
if you really need a container that 1) contains actual
objects (i.e. copies of what you insert), and 2) can contain
absolutely anything you throw at it, then this is probably the
only answer. Most of the time I've needed heterogenous
containers, however, the items in question have 1) been related
(and had a common base class), and 2) had identity (which means
that I don't want to copy them), so a container of pointers to
the base class was the answer.
The reason I want to know is I am about to try my hands at learning
classes and need to do it in a way I can grasp - ala gaming concepts
(see inventory example above.)
I'm not familiar enough with games programming to be sure, but I
suspect that the objects that you would put into a backpack
would have identity, so you don't want to deal with copies, only
the original. Also, I wouldn't be surprised if they had a
common base class: in the one game I'm fairly familiar with
(nethack), all objects, regardless of their category, have
weight, can be named, and listed, etc.---common functionality
which could reasonably be expected to be in a base class.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 25 '07 #8
Salt_Peter wrote:
On May 24, 1:48 pm, Devon Null <theronnights.. .@xgmailx.comwr ote:
>Salt_Peter wrote:
>>On May 24, 12:30 pm, Devon Null <theronnights.. .@gmail.comwrot e:
I was wondering if there is a container (i.e. a vector) that can hold
data structures of differing sizes. I was thinking of something along
the lines of a container of classes. Think of a backpack you can take
items from and put items into of different sizes.
The reason I want to know is I am about to try my hands at learning
classes and need to do it in a way I can grasp - ala gaming concepts
(see inventory example above.)
Thanks in advance.
The backpack isn't storing the specifications of each item.
It simply stores objects, not classes.
It can also store base pointers to derived entities (which is what you
are looking for).
Assuming you have some form of inheritance hierarchy:
class Item {
virtual ~Item() = 0;
};
Item::~Item () { }
class Weapon : public Item { };
class Potion : public Item { };
int main()
{
// Item item; // error, Item is abstract
Weapon weapon;
Potion potion;
std::vector< Base* inventory;
inventory.push_ back( &weapon );
inventory.push_ back( &potion );
}
I'ld suggest keeping the base class abstract.
Types Weapon and Potion have their own specific attributes and their
own specific member functions.
Once you are comfortable with such a scenario, do look into smart
pointers (ie: boost:shared_pt r).
Otherwise, you'll need to manage the lifetime of those Items.
Took me a second but I think I see what is going on here with the base
class. I can see where that could be a nightmare in maintenance.I
grabbed a couple of .h files fromhttp://ootips.org/yonat/4dev/that
should help.

Consider using boost's shared_ptr instead
>Another question - say I was to use this example, would my class
declarations go inside the braces in the statement

class Weapon : public Item { /*in here?*/ }; ?

yes, keep in mind that different parts of your hierarchy will have
their own attributes and responsabilitie s. Example: an AssaultRifle
is_a type of Weapon which is_a type of Item.
>Like I said, I am actually just about to jump into classes. I also
assume that I would do that for any class inheriting the public parts of
class Item (i.e. any items).

Not really. Consider that all items have a weight/mass. Item's
derivatives need not handle that aspect so you'ld keep weight in Item,
no virtual getweight() function needed. Weapon might itself become a
base class for concrete weapons (ie, rifle, laser, grenade, etc). All
weapons can fire() but each weapon fires in its own way. A rifle might
have an ammo count. And so on. See if the code below clarifies some
issues, i'm completely ignoring the fact that an Item needs to be
loaded/equipped.

Note how lifetimes are greatly simplified by the use of
boost::shared_p tr.

#include <iostream>
#include <vector>
#include <string>
#include <boost/shared_ptr.hpp>

class Item {
double weight;
protected:
Item(double w = 0.0) : weight(w) { }
public:
~Item() { std::cout << "~Item()\n" ; }
double getweight() const { return weight; }
virtual void use() = 0;
};

class Weapon : public Item
{
protected:
Weapon(double w = 0.0) : Item(w) { }
virtual void fire() = 0;
};

class AssaultRifle : public Weapon
{
int ammo;
public:
AssaultRifle(in t a = 16) : Weapon(20.1), ammo(a)
{
std::cout << "AssaultRifle() \n";
}
~AssaultRifle() { std::cout << "~AssaultRifle( )\n"; }
void use()
{
fire();
std::cout << "fired!, ammo left :" << ammo;
std::cout << std::endl;
}
private:
void fire() { --ammo; }
};

int main()
{
typedef boost::shared_p tr< Item SPtrItem;
std::vector< SPtrItem inventory;
inventory.push_ back( SPtrItem( new AssaultRifle(32 ) ) );

std::cout << "inventory[0]'s weight is: ";
std::cout << inventory.at(0)->getweight();
std::cout << std::endl;

inventory.at(0)->use(); // universal Item user
}

/*
AssaultRifle()
inventory[0]'s weight is: 20.1
fired!, ammo left :31
~AssaultRifle()
~Item()
*/
That's gonna take me a minute to sort out. I'll have to definitely
study that. Thanks for the example. It gives me something concrete to
see and understand just how it works. I haven't gotten to inheritance in
the book I am reading yet - Beginning C++ Through Game Programming SE -
but this will go miles in helping me to understand.
May 25 '07 #9

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

Similar topics

10
3054
by: Jason | last post by:
Hi, I have a few million data items being received by my program and I wish to store them in a list, with each item being inserted in any position in the list. Any performance tips so that my program runs ok? I have checked out the STL and have thought of using vector, set, list, deque and map. I dont know how these things are implemented so not sure which is best to use or if i should implement another data structure. Perhaps any...
4
1892
by: matthurne | last post by:
I am working through exercise 8-2 in Accelerated C++...I am implementing the function equal(b, e, b2) where b is an iterator for the first element in a container, e is an iterator pointing to one past the last element in that same container, and b2 is an iterator for the first element in the second container. Here's what I have: template <class T> bool equal(T begin, T end, T begin2) { while (begin != end) { if (*begin != *begin2) {
6
6908
by: Smutny30 | last post by:
Hello, I consider partitioning a huge table. I am not sure wheather it is possioble only in partitioned databases. I found somewhere in docs ( http://tinyurl.com/4oara ) that there are (simple, segmented and partitioned) tablespaces. What is segmented tablespace ? Is it possible to span the the tables within multiple containers (but in some ordered manner) with no db partitions ?
8
5114
by: Ross A. Finlayson | last post by:
I'm trying to write some C code, but I want to use C++'s std::vector. Indeed, if the code is compiled as C++, I want the container to actually be std::vector, in this case of a collection of value types or std::vector<int>. So where I would use an int* and reallocate it from time to time in C, and randomly access it via , then I figure to copy the capacity and reserve methods, because I just need a growable array. I get to considering...
73
4626
by: Claudio Grondi | last post by:
In the process of learning about some deeper details of Python I am curious if it is possible to write a 'prefix' code assigning to a and b something special, so, that Python gets trapped in an endless loop in a line with: if a==b: print 'OK' I mean, it would be of much help to me on my way to understanding Python to know how such prefix code leading to an endless loop can look like and if it is eventually not possible to write such...
9
4548
by: nicolas.michel.lava | last post by:
Hi there, I have some trouble using STL containers. I'm working on a multithreaded (pthread) application making heavy usage of STL containers. All accesses to containers are made in locked sections (using mutexes). But sometimes it happens that the application crashes on container operations. The 2 last crashes are : * calling push_back on a stl::list object (the backtrace show the last call was in stl::list::insert); * accessing an...
4
1795
by: Michel Esber | last post by:
Hello, LUW V8 FP 11 running Linux RH AS4 Update 3. In regards to performance and IO parallelism, does it matter if I create a tablespace with a single big container, or is it better to create it with several smaller containers ? Any ideas and links to the proper documentation is greatly appreciated.
4
2585
by: Michel Esber | last post by:
Hello, DB2 V8 FP12 LUW. My system is under heavy wait-io times. I have read the following article: http://tinyurl.com/p844z and it says that prefetchsize should be the product of extentsize and the number of containers.
0
4103
by: zhif | last post by:
I tried to test this process on my personal laptop. Could you help me to take a look where is the problem as below? 1. I created a source database, name: db100 <-- db2 create db db100 2. Collect the source database tablespace containers’ information <-- db2 list tablespace containers for 0 show detail Then I got as below Tablespace Containers for Tablespace 0 Container ID = 0 Name ...
0
9423
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
10210
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10043
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
9990
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
9861
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...
0
8869
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6672
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
5298
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3956
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

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.