For 2,3 tasks you could do:
(对于2,3个任务,您可以执行以下操作:)
The code:
(代码:)
int task2and3(const std::map<std::string,int>& m, bool trueIfIsNot)
{
std::vector<std::pair<std::string,int>> vec(m.size());
auto firstPastEnd = std::copy_if(m.begin(),m.end(),vec.begin(),
std::bind(checkEmpty,std::placeholders::_1,trueIfIsNot));
std::for_each(vec.begin(), firstPastEnd,
std::bind(print,std::bind(split,std::placeholders::_1)));
return firstPastEnd - vec.begin();
}
by trueIfIsNot
you indicate which pairs are printed (with value as 0 or otherwise).
(通过trueIfIsNot
指示要打印的对(值等于0或其他值)。)
To do 4-th task, you could also use vector
to store items of map
.
(要执行第4项任务,您还可以使用vector
存储map
项目。)
To remove elements from map you could iterate over these items in vector (using for_each
) and call map::erase
method. (要从map中删除元素,您可以遍历vector中的这些项目(使用for_each
)并调用map::erase
方法。)
Because this function member has overloads, you need to cast it properly to indicate method removing elements by key_type
. (由于此函数成员具有重载,因此需要正确地对其进行key_type
以指示通过key_type
删除元素的key_type
。)
Use split
to get this key_type
from pair. (使用split
从对中获取此key_type
。)
void task4(std::map<std::string,int>& m)
{
std::vector<std::pair<std::string,int>> vec(m.size());
auto firstPastEnd = std::copy_if(m.begin(),m.end(),vec.begin(),std::bind(checkEmpty,std::placeholders::_1,false));
using sizeType = std::map<std::string,int>::size_type;
using keyType = std::map<std::string,int>::key_type;
for_each(vec.begin(), firstPastEnd,
std::bind( static_cast<sizeType (std::map<std::string,int>::*)(const keyType&) >(&std::map<std::string,int>::erase),
&m,
std::bind(split,std::placeholders::_1)) );
}
Full demo
(完整演示)