Can there be a vector of references?

Hi guys.

Is there a way, beside using pointers that an object be kept in two vectors?

For example, the following code:

1
2
3
4
5
6
7
8
9
10
11
12
vector<int> a;
vector<int> b;

int c = 2;

a.push_back(c);
b.push_back(c);

a[0] = 1;

cout << a[0] << "\n"; 
cout << b[0] << "\n";


Will give:

1
2
1
2


Is there a way to change it so that the output will be
1
2
2
2

?

Thanks
What do you mean? With or without changing line 9?
Last edited on
I'm sorry. I mixed things up.

The output I want is this:

1
2
1
1


This code would do that
1
2
3
4
5
6
7
8
9
10
11
vector<int*> a;
	vector<int*> b;
	
	int c = 2;
	
	a.push_back(&c);
	b.push_back(&c);
	(*a[0]) = 1;
	
	cout << (*a[0]) <<"\n";
	cout << (*b[0]) <<"\n";


But I don't want to use pointers.
pointers are evil
http://www.parashift.com/c++-faq-lite/big-picture.html#faq-6.15

I'm just not used to pointer thinking.
As far as I can understand, you should avoid the usage of pointers.

Thanks any way.
You could do a wrapper class that encapsulates the process, using a reference counting smart pointer.
http://ootips.org/yonat/4dev/counted_ptr.h
Boost has facilities for both pointer containers and smart pointers.
Thanks.

I really don't want to dive into more code right now, I'm overwhelmed as it is.
As for boost, once I get my new machine I'll check it.

In the meantime, if I have a vector of a class which holds pointers. when I access an element of the vector using iterator:

1
2
vector<Foo>::iterator it = Bar.begin();
Foo aFoo = *it;


what does aFoo holds? a copy of the element in the vector or the element itself. More important, are the pointers the same?

Thanks
You can get a reference or a copy of the element in the container. I'm pretty sure this is valid, for a vector. If you are using an associative container, you might find that the element is const while it is contained.
1
2
3
4
5
vector<Foo> bar;
vector<Foo>::iterator i = bar.begin();

Foo copy( *it );
Foo & reference( *it );

Topic archived. No new replies allowed.