I am currently in the process of learning C++17 and we were given a challenge as part of practicing using the Standard library to get used to using the features:
(我目前正在学习C ++ 17,作为练习使用标准库以习惯使用这些功能的一部分,我们遇到了挑战:)
- Iterate over a
std::map<std::string, size_t>
(also known asstd::map<file_name, file_size>
)(遍历
std::map<std::string, size_t>
(也称为std::map<file_name, file_size>
)) - Print file names that are empty
size_t == 0
and return its count(打印为空的文件名
size_t == 0
并返回其计数) - Print file names that are not empty
size_t != 0
and return its count(打印不为空的文件名
size_t != 0
并返回其计数) - Removing from map
std::pairs
whose size_t == 0
(从map
std::pairs
删除,whose size_t == 0
)
Restrictions:
(限制条件:)
Can only use headers:
<vector>
,<map>
,<string>
,<algorithm>
,<functional>
(只能使用标头:
<vector>
,<map>
,<string>
,<algorithm>
,<functional>
)Cannot define complex types nor templates
(无法定义复杂类型或模板)
Cannot use the
. (member access), -> (member access via pointer), * (dereference) operators
(无法使用
. (member access), -> (member access via pointer), * (dereference) operators
). (member access), -> (member access via pointer), * (dereference) operators
Cannot use
for, while, do-while nor if-else, switch
and other conditionals(不能
for, while, do-while nor if-else, switch
和其他条件)Can use
std::for_each
and other functions of function templates to iterate over collection of elements(可以使用
std::for_each
和功能模板的其他功能来迭代元素集合)No lambdas
(没有lambdas)
No
std::cout
,std::cerr
,std::ostream
etc.(没有
std::cout
,std::cerr
,std::ostream
等。)No auto types
(没有自动类型)
Can use other functions so long as they are included in the headers described at restriction #1
(可以使用其他功能,只要它们包含在限制1中所述的标头中)
Allowed to use these functions:
(允许使用以下功能:)
void print(const std::string& str)
{
std::cout << str << std::endl;
}
std::string split(const std::pair<std::string, size_t> &r)
{
std::string name;
std::tie(name, std::ignore) = r;
return name;
}
bool checkEmpty(const std::pair<std::string, size_t>& r, bool trueIfIsNot
)
{
file_size size;
std::tie(std::ignore, size) = r;
bool result = (size == 0);
if (trueIfIsNot)
{
result = !result;
}
return result;
}
I have began to appreciate the use of std::bind
and std::for_each
in my previous post.
(在我以前的文章中,我开始欣赏std::bind
和std::for_each
的使用。)
(这次,我如何添加谓词和条件以修改输出,而无需使用限制#4所述的语法?)
I am currently considering using std::transform()
or maybe std::copy_if()
etc. I have some understanding of many of the Standard Library's functions but i think i am very weak at the syntax to understand how things work together so i do not know how to make use of them.
(我目前正在考虑使用std::transform()
或std::copy_if()
等。我对许多标准库的功能都有一定的了解,但是我认为我在语法上很虚弱,无法理解事情如何协同工作,所以我不知道如何利用它们。)