Pages

Friday, May 31, 2013

Deleting elements in map: C++ and Python

C++

std::listlist<int> keys;
// 1. get all the keys that has the elements from bList
for (std::listlist<int>::iterator it = bList.begin(); it != bList.end(); ++it)
{
    for (std::map<string, int>::iterator j = aMap.begin(); j != aMap.end(); ++j)
    {
        if (j->second == *it) keys.push_back(j->first);
    }
}

// 2. remove all the items of the key
for (auto it = keys.begin(); it != keys.end(); ++it)
{
    aMap.erase(*it);
}
std::list<int> keys;
for (auto it = bList.begin(); it != bList.end(); ++it)
{
    for (auto j = aMap.begin(); j != aMap.end(); ++j)
    {
        if (j->second == *it) keys.push_back(j->first);
    }
}

// 3. remove all the items of the key
for (auto it = keys.begin(); it != keys.end(); ++it)
{
    aMap.erase(*it);
}

Python

http://stackoverflow.com/questions/11277432/how-to-remove-a-key-from-dictionary
for e in elements:
    if e in aDict:
        del aDict[e]
for e in elements:
	aDict.pop(e, None)

No comments:

Post a Comment