[英]Is there a way of creating a shorthand map to be passed to a function in C++?
I wonder if there is a way of constructing a temporary map to be passed so that the following implementation is possible:我想知道是否有一种方法可以构建要传递的临时映射,以便可以进行以下实现:
void func(map<string,int> & input) {
cout << input["m1"] << endl;
cout << input["m2"] << endl;
}
func ( map<string,int>{{"m1",1},{"m2",2}} ; // causing error when compiled
The problem is that you're trying to bind an rvalue expression to an lvalue reference to non-const std::map
.问题是您试图将右值表达式绑定到对非常量
std::map
的左值引用。
To solve this you can add a low-level const
in the parameter and use std::map::find
as shown below:要解决这个问题,您可以在参数中添加一个低级
const
并使用std::map::find
,如下所示:
void func(const std::map<string, int>& input) {
auto it1 = input.find("m1");
if(it1!=input.end())
{
cout << it1->second << endl;
}
else
{
std::cout<<"element cannot be found"<<std::endl;
}
//do the same for other key "m2"
}
int main()
{
func({{"m1", 1}, {"m2", 2}});
return 0;
}
Note if you want to just print all the elements of the map you can use structure binding with C++17 as shown below:请注意,如果您只想打印地图的所有元素,您可以使用 C++17 的结构绑定,如下所示:
void func(const std::map<string, int>& input) {
for(const auto&[key, value]: input)
{
std::cout<<key<<" --> "<<value<<std::endl;
}
}
int main()
{
func({{"m1", 1}, {"m2", 2}});
return 0;
}
Demo C++17 & above演示 C++17 及更高版本
Note structure bindings are available from C++17, so if you're using C++11 or C++14 you can use the range-based for loop :注意结构绑定可从 C++17 获得,因此如果您使用 C++11 或 C++14,您可以使用基于范围的 for 循环:
void func(const std::map<string, int>& input) {
for(const auto&element: input)
{
std::cout<<element.first<<" --> "<<element.second<<std::endl;
}
}
Generally, yes, that's easily possible, you just need to make your func
accept temporary (rvalue) values.通常,是的,这很容易实现,您只需要让您的
func
接受临时(右值)值。
You don't need to modify the map, so你不需要修改地图,所以
void func(const std::map<string, int>& input) {
cout << input.at("m1") << endl;
cout << input.at("m2") << endl;
}
func({{"m1", 1}, {"m2", 2}});
should do.应该做。
Note that, as comfortable as they are, []
of map modifies the map (if there key is not in there before, it's inserted and a value is value-initialized).请注意,尽管它们很舒服,但 map 的
[]
修改了 map(如果之前没有键,则插入它并且值初始化)。 So, you can't use it on const references.所以,你不能在 const 引用上使用它。
The way around that is passing in the map as special rval ref, &&
:解决方法是在地图中作为特殊的 rval ref 传递
&&
:
void func(map<string,int>&& input) {
cout << input["m1"] << endl;
cout << input["m2"] << endl;
}
However, that is not always the right thing to do, and I do prefer the const & approach when the function really has no need to modify the parameter, as it actually makes compile-time guarantees that this won't happen, even on complex objects.然而,这并不总是正确的做法,当函数真的不需要修改参数时,我确实更喜欢 const & 方法,因为它实际上使编译时保证不会发生这种情况,即使在复杂的情况下对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.