newbarker
9/11/2008 2:24:00 PM
On 11 Sep, 05:14, Rolf Magnus <ramag...@t-online.de> wrote:
> swtsvn wrote:
> > hi all
> > iam trying to use list from stl
> > and i did not find any method to update the value of a list item
> > for example
> > listvalue++ for each node in the list
> > could any of u tell me how to update a value in the list?
>
> Use an iterator and dereference it. For the specific case of incrementing
> each element, you can use for_each:
>
> // #include <algorithm> and <functional> before this
> // replace value_type with the elemnt type of your list.
> for_each(mylist.begin(), mylist.end(), bind2nd(plus<value_type>(), 1));
>
> Anything other than such trivial examples is best done using an ordinary for
> loop iterating from begin() to end().
for_each doesn't quite do it - think it will throw the return value
away. transform will update the container, so this works and outputs
"2,3,4,"
#include <algorithm>
#include <functional>
#include <iostream>
#include <list>
using namespace std; // For brevity in this e-mail
int main()
{
std::list<int> li;
li.push_back(1);
li.push_back(2);
li.push_back(3);
transform(li.begin(),li.end(),li.begin(),bind2nd(plus<int>(),1));
copy(li.begin(),li.end(),ostream_iterator<int>(std::cout,","));
}