Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Accessing & Updating an STL list

0 views
Skip to first unread message

Mike Copeland

unread,
Feb 28, 2009, 4:26:53 PM2/28/09
to
I have the following structure and STL list declaration and code that
builds the list objects. Now, I want to easily search the list for
matches (on sValue) and when found increment the "nCount" field in the
matched object.
(This) seems simple enough, but I can't find any function in the STL
that allows me to alter/change the list elements. I also know that I
can loop through the list with a "for" loop, but isn't there an easier
way to "find" an element in an STL list?
Any thoughts? TIA...

struct SPECIAL_AGES
{
string sValue;
string sDescription;
int newAge;
int nCount;
char cGender;
} aWork;
typedef list<SPECIAL_AGES> SPAGES;
SPAGES aList;
SPAGES::iterator aIter;
...
aWork.cGender = 'M';
[etc.]
aList.push_back(saWork);

Victor Bazarov

unread,
Feb 28, 2009, 7:03:26 PM2/28/09
to

Read about 'std::transform' function and 'std::for_each'. The
simplest thing probably would be to define your own functor that
compares the value of 'sValue' and does what you need.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask


Kai-Uwe Bux

unread,
Feb 28, 2009, 7:28:58 PM2/28/09
to
Mike Copeland wrote:

> I have the following structure and STL list declaration and code that
> builds the list objects. Now, I want to easily search the list for
> matches (on sValue) and when found increment the "nCount" field in the
> matched object.
> (This) seems simple enough, but I can't find any function in the STL
> that allows me to alter/change the list elements.

Changing the elements of the list (as opposed to inserting or erasing
elements) is done through the iterator. If you have a list<T>::iterator,
say iter, then the expression *iter has type T& and gives you a reference
to the element referred to by iter. Similarly, you can use iter->some_field
to access fields.

> I also know that I
> can loop through the list with a "for" loop, but isn't there an easier
> way to "find" an element in an STL list?

List only support sequential search. You can hide this search in an
algorithm like for_each, find, transform, or whatever; but under the hood
it will remain a sequential search. That said, hiding the detail can be
right and amount to chosing the appropriate level of abstraction.


Best

Kai-Uwe Bux

0 new messages