I have no experience on C++ but recently need to rewrite a C++ project in Python. I met several problems that I failed to solve them and some of them are below:
Problem 1
Let's say that there's a map sampleMap
and an integer anConstant
in C++ code:
for (typename map <string, vector <pair <unsigned int, int> > >::iterator l = sampleMap.begin(); l != sampleMap.end(); ) {
if (l->second.size() < anConstant) {
typename map <string, vector <pair <unsigned int, int> > >::iterator tmp = l;
tmp = l; ++tmp; sampleMap.erase (l); l = tmp;
} else {
++l;
}
}
In my understanding, what the code means is that a (key, value)
pair should be removed from the map sampleMap
if the value's (actually a vector) size is smaller then the integer (anConstant
).
So I rewrote the code in Python in below:
for key, value in sampleMap.copy().items():
if len(value) < anConstant:
del sampleMap[key]
But seems that it didn't work correctly. Maybe I misunderstood what the c++ code said, can anyone kindly help me to understand the c++ code?
Problem 2
Same, let's say there's a map named sampleMap
, a vector named sampleVector
, two constants named constantOne
and constantTwo
.
for (typename map <string, vector <pair <unsigned int, int> > >::iterator l = sampleMap.begin(); l != sampleMap.end(); ++l) {
if (sampleVector.size() - constantOne < constantTwo){
sampleVector.push_back(make_pair <string, unsigned int> (l->first, l->second.size()));
sampleVector.erase(sampleVector.end());
}
}
In my understanding, the code is saying that while looping the map sampleMap
if the condition in the if
statement is met, then make the (key, value)
's size a new pair and append the pair into sampleVector
.
But I don't understand the last sentence: It doesn't seem to try to remove the last element in the vector. So what does it do? The code runs correctly.
Please kindly help me to understand the c++ code. Thank you!
================EDIT==================
Thank you all for the solution!
For problem 1, after tested the c++ code and python code I found that the python code worked well. Anyway I made sure what the c++ code means, I learnt a lot :P
For problem 2, I still don't know what sampleVector.erase(sampleVector.end())
does here, but I tried to rewrite it as del sampleVector[-1]
(to delete the last item of sampleVector) here and the output was as same as the one of c++ code. How strange is it! I will open a new post to discuss this problem and will give the new link here.
Again, thank you all! :D