list edit

S

swtsvn

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?
 
R

Rolf Magnus

swtsvn said:
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().
 
N

newbarker

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,","));
}
 
R

Rolf Magnus

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,"

Yes, you're right. I shouldn't post in the moring when I'm in a hurry.
 

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,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top