I have a list
of pair
s with CString
s and want to iterate over it and use first
and second
elements of each pair
in the list
inside the for
loop, but I have a problem with doing that. Can someone explain to me why this doesn't work and help me with the solution?
This is my code:
list<pair<CString, CString>*> listSubstStr;
for (std::list<pair<CString, CString>*>::iterator it = listSubstStr.begin(); it != listSubstStr.end(); ++it) {
CxXML* p = pRoot->AddTag(NOWKT("Pair"));
p->SetString("First", it->first);
p->SetString("Second", it->second);
}
Here are the errors:
It seems you mean
p->SetString("First", ( *it )->first);
p->SetString("Second", ( *it )->second);
That is the expression *it
has the type pair<CString, CString>*
.
Also check whether this code is called within a constant member function. If so then you have to use const_iterator instead of iterator.
Look at your types.
You're iterating over a list<pair<CString, CString>*>
, so the elements are pair<CString, CString>*
.
That means that *it
is also a pointer, so you need to dereference twice:
(*it)->first
or use the modern range loop:
for (auto element: listSubstStr)
{
CxXML* p = pRoot->AddTag(NOWKT("Pair"));
p->SetString("First", element->first);
p->SetString("Second", element->second);
}
(The use of std::list
and of pointers to pairs are both questionable, by the way. The more common choice would be vector<pair<CString, CString>>
.)
You have a list<pair<CString, CString>*>
ie a list of pointers to pair<CString,Cstring>
.
Dereferencing an iterator will get you a pair<CString, CString>*&
. Hence to get the pair you need to dereference the iterator, then the pointer: (*it)->first
.
It is rather likely that you didnt need pointers in the first place.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.