How to change an element from a LIST

I simply want to iterate trought a list and if I discover some value at some posittion to change it ,How ?
I have searched over the net, but I have not view the solution.
Any help ? Thanks
Thanks, it can be a solution.

But in case I use a lot of compare sentences :

1
2
3
4
5
6
7
8
9
list<std::string>::iterator i;

    for ( i=LIST.begin() ; i != LIST.end(); i++ )
    if (*i==a_value) 
    replace

    if (*i==b_value) 
   replace
 ....


I dont know if this method are going fast than 'replace_if'
There is not a replace command using the iterator?

If I have to get the values using the iterator method, why there is not a method using it ?


Thanks
Something like this?
1
2
3
4
5
6
7
8
9
10
typedef list< std::string > Cont;
for( Cont::iterator i = LIST.begin(); i != LIST.end(); ++i ) {
    // dereference the iterator to get a reference to the element
    std::string & s( *i );
    // test it
    if( s == "something" ) 
        s = "something else";         // replace
    if( s == "another something" ) 
        s = "another something else"; // replace
}

You can assign directly to *i, if that's what you mean. I still suggest encapsulating the test and replace logic in a function object and using a std algorithm.
Last edited on
Thanks
The solution is based in handling the pointers, isn't?
I was now reading something like your solution.
Thanks again.
mmm
I need more help, I dont understand the pointers.....

std::string & s( *i );
How would can I create 's' to have the reference of i if the var is created before the for-loop ?
That is :

1
2
3
4
5
std::string s;
for () 
{
    s=&( *i );  ????
}


And , I need to change the next element of the list if I found a value, so :

1
2
3
     if( s == "something" ) 
        s = "something else";         // replace
        s= &( *i++ ); ??????


I'm doing some combinations but I can't get the right way.
Thanks a lot
Last edited on
The variable is a reference and can be created inside the loop--it is not copying anything. References cannot be left uninitialized nor can they be changed. You would have to use a pointer or take the variable by value if you insist on moving the declaration out of the loop.
I know that you probably have to do better things than waste the time with me...
But could you write some code for the example ?
I' working with it, but I can't get nothing....
Thanks
Topic archived. No new replies allowed.