Archived

This topic is now archived and is closed to further replies.

Linked List & Reference and/or Point :: STL

This topic is 5590 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi. I would like to is it possible to pass a reference and/or a pointer of an element in a linked list as function parameter? For example:
std::list intList;

for (int i = 0; i < 5; ++i)
intList.push_back(i);

std::list::iterator iNumList = intList.begin();

// Traverse to element #4
for (int j = 0; j < 3; ++j
++iNumList;

// Now I want to pass element #4 (interger 4) to a function.
// Is it possible to point a reference or pointer to iNumList?

myFunction(iNumList);
...

void myFunction(int *pNumber)
{
...
*pNumber = 0;
...
}
 
Thanks, Kuphryn

Share this post


Link to post
Share on other sites
either :


  

void func(int* val) {
*val = 10;
}

std::list< int >::iterator it = someList.begin();
while(it != someList.end())
{
func( *it );
++it;
}



or


  

void func(std::list<int>::iterator &val) {
*val = 10;
}

std::list< int >::iterator it = someList.begin();
while(it != someList.end())
{
func( it );
++it;
}

[/souce]

Share this post


Link to post
Share on other sites
If you pass the iterator, you can remove the item it points to from the list. AFAIK, there is no way to do this if you pass a pointer (unless you find the element).

Cédric

Share this post


Link to post
Share on other sites
quote:
Original post by kuphryn
Nice! Thanks.

Is there an advantage to using one solution over the other?

Kuphryn


not really, in fact it''s actually quite bad to do that because there are already fun funky things in stl sontainers that simplify the process and are somewhat more optimised, for example:


  
// need this for std::for_each

#include <algorithm>
#include <list>

void func(int &val)
{
val = 10;
}

std::list< int >::iterator start = someList.begin();
std::list< int >::iterator end = someList.end();

std::for_each(start, end, func );


have a look at

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclang98/html/sample_for_each_(STL_Sample).asp

for a variety of other similar algorithmic constructs.....

Rob

Share this post


Link to post
Share on other sites