从 C++11 开始,您可以使用聚合初始化:
void foo(std::map<std::string, std::string> myMap = {});
例子:
#include <iostream>
#include <map>
#include <string>
void foo(std::map<std::string, std::string> myMap = {})
{
for(auto it = std::cbegin(myMap); it != std::cend(myMap); ++it)
std::cout << it->first << " : " << it->second << '\n';
}
int main(int, char*[])
{
const std::map<std::string, std::string> animalKids = {
{ "antelope", "calf" }, { "ant", "antling" },
{ "baboon", "infant" }, { "bear", "cub" },
{ "bee", "larva" }, { "cat", "kitten" }
};
foo();
foo(animalKids);
return 0;
}
你可以在Godbolt上玩这个例子。