why vector<int&> is not allowed?

A

Andy

Hi,

Could you explain why vectora<int&> is not allowed?
For example, the following prgram will be given compilation error.

#include <vector>
using namespace std;

int main()
{
vector<int&> myvec;
return 0;
}


Thanks!

Andy
 
M

Mike Wahler

Andy said:
Hi,

Could you explain why vectora<int&> is not allowed?

Because vector (and other containers) can only store
objects, and a reference is not an object. It's simply
an alternative name for an existing object. Containers
store objects, not names.
For example, the following prgram will be given compilation error.

And rightly so.
#include <vector>
using namespace std;

int main()
{
vector<int&> myvec;
return 0;
}

BTW why do you feel the need to try to store a
collection of references? You can (and often
should) use a reference to a container, e.g.
as a function parameter, which eliminates the
need for a copy operation when the function is called
(C++ passes function arguments by value by default).

-Mike
 
L

laniik

might you be wanting to do

int main()
{
vector<int*> myvec;
return 0;
}

instead? Not sure why you would need an array of references. pointers
tho, that could be useful.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top