vector that holds two items

Mar 4, 2012 at 6:17am
Need to make a vector that stores two object, so that each index of the vector has 1. a generic object
2. a float object.

What's the best way to do this? I don't want to have an inner class with getters and setters, are there any other possibilities?
Mar 4, 2012 at 7:04am
¿eh?
std::pair< generic_object, float_object >
Mar 4, 2012 at 7:23am
Without using the STL...
Mar 4, 2012 at 7:37am
How about using a struct? (I'm not really sure if typename can be used to define though).
1
2
3
4
5
struct pair
{
    typename generic_object;
    float float_object;
};



EDIT: okay that didn't work. But how about this? It'll store your generic object as a void pointer. Then return the address to it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class pair
{
	void* generic_object;
	int generic_size;
	float float_object;
public: 
	// Set functions
	void setFloat(float _f) { float_object = _f; }
	template <class T> void setGeneric(const T& t) { generic_object = &t; }
	
	// Get functions
	float getFloat() { return float_object; }
	void* getGeneric()	{ return generic_object;	}
};

The trick is that I'm not sure how to keep the memory reserved. If the original object is destroyed then I think this pointer just points to an empty place in memory.
Last edited on Mar 4, 2012 at 7:48am
Mar 4, 2012 at 7:57am
1
2
3
4
5
6
7
8
9
10
11
template < typename T > struct my_pair
{
    T generic_object ;
    float float_object ;

    // constructors etc
};

// ....

std::vector< my_pair<std::string> > my_vector ;

Mar 4, 2012 at 8:00am
Okay that works better.
Mar 4, 2012 at 9:05am
aka reinventing the wheel
Mar 5, 2012 at 12:28am
Is there any way to do this using pointers, avoiding an inner class? [see OP]
Mar 5, 2012 at 12:33am
Make two vectors
Topic archived. No new replies allowed.