Re: Modifying STL list Objects
On May 23, 11:49 pm, mrc2...@cox.net (Mike Copeland) wrote:
I continue to have problems working with STL containers of
structures, and nothing in Google searches addresses the kind of things
I'm doing. 8<{{
My (latest) problem is that although I can populate a list, I can'=
t
see how to access a specific object and update it. The application her=
e
is one which I'm counting the occurrences of Cities & States in a data
file - I chose a list to do this work because I need to sort the list
after it's build and report by State.
If you are counting "occurances" then you are also better off with
std::map<std::string, int>. If sorting order is the natural sorting
order for std::string then map is a sorted container which means that
you will not need to any extra work.
struct ENTLOCS
{
string sortKey;
string ctsKey;
string stateName;
string cityName;
int eCount;
bool operator <(const ENTLOCS &rhs) const // comparison operator
{
return stateName < rhs.stateName;
}} eWork;
[...]
char s80[80];
list<ENTLOCS> hStats;
list<ENTLOCS>::iterator eIter;
[...]
while(fv1.readln(s80, true)) // note: my own I/o routine...
{
bool bFound = false;
eWork.ctsKey = sCTS, eWork.cityName = CTSCity;
eWork.stateName = CTSState;
eWork.sortKey = CTSState, eWork.sortKey +=CTSCity;
for(eIter = hStats.begin(); eIter != hStats.end(); eI=
ter++)
{
ENTLOCS eTemp = *eIter;
if(eTemp.ctsKey == sCTS)
{
bFound = true; break;
}
} // for
if(bFound == false)
{
eWork.eCount = 1;
hStats.push_back(eWork);
}
else
{
ENTLOCS eTemp = *eIter;
eTemp.eCount++; // this doesn't work... 8<{{
What is exactly meant by "doesn't work"? Does it not compile well?
does it not increment eTemp.count?
BTW Note that you are "copying" the list element *eIter in eTemp. This
means that any changes made to eTemp will _not_ reflect in *eIter.
Essentially, eTemp.eCount++ does _not_ increment eIter->eCount. If you
want that, make eTemp a reference and avoid the copy:
ENTLOCS& eTemp = *eIter;
eTemp.eCount++; // This is same as eIter->eCoun=
t++;