STL vector : can not use begin() and end() on function return

L

linq936

Hi,
I have some code like this,

vector<MyNode*> getNodes() {
return theNodes;
}

int func() {
vector<MyNode*> nodes;
nodes.insert(nodes.end(), getNodes().begin(), getNodes().end());

}


This code crashes on Windows using VC7 compiler. In debuging it I
find that I have to change the code to:

int func() {
vector<MyNode*> nodes, tmp_nodes;
tmp_nodes=getNodes();
nodes.insert(nodes.end(), tmp_nodes.begin(), tmp_nodes.end());
}


It looks like I can use begin() and end() directly to a function
return, but I am wondering why?
 
D

David Harmon

On 10 Sep 2006 20:55:36 -0700 in comp.lang.c++, (e-mail address removed)
wrote,
vector<MyNode*> getNodes() {
return theNodes;
}


The above returns a copy of "theNodes" to the caller.
int func() {
vector<MyNode*> nodes;
nodes.insert(nodes.end(), getNodes().begin(), getNodes().end());

}

The above calls getNodes twice, getting two copies of theNodes. It
then tries to compare the .begin() of one of them to the .end() of
the other one. They are not comparable since they belong to two
different vectors. Boom.
 
T

tragomaskhalos

Hi,
I have some code like this,

vector<MyNode*> getNodes() {
return theNodes;
}

int func() {
vector<MyNode*> nodes;
nodes.insert(nodes.end(), getNodes().begin(), getNodes().end());

}

I suspect you want this:

vector<MyNode*> const & getNodes() { // nb return type
return theNodes;
}

void func() {
vector<MyNode*> nodes;
nodes.insert(nodes.end(), getNodes().begin(), getNodes().end());
}
 
C

Clark S. Cox III

Hi,
I have some code like this,

vector<MyNode*> getNodes() {
return theNodes;
}

int func() {
vector<MyNode*> nodes;
nodes.insert(nodes.end(), getNodes().begin(), getNodes().end());

}


This code crashes on Windows using VC7 compiler. In debuging it I
find that I have to change the code to:

int func() {
vector<MyNode*> nodes, tmp_nodes;
tmp_nodes=getNodes();
nodes.insert(nodes.end(), tmp_nodes.begin(), tmp_nodes.end());
}


It looks like I can use begin() and end() directly to a function
return, but I am wondering why?


Each time you call getNodes() in that last line of func(), you get a new
copy of theNodes.

You basically have two choices:

1) Use a temporary variable as you do above.
2) Change getNodes to return a reference, like so:
const vector<MyNode*> &getNodes() {
return theNodes;
}

#2 has the advantage that it doesn't cause a new copy of theNodes to be
made.
 

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

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top