【问题标题】:Can I create a new map on the fly and pass as a function parameter?我可以即时创建新地图并作为函数参数传递吗?
【发布时间】:2020-05-18 01:10:01
【问题描述】:

在 C# 中,我可以这样:

        public static Dictionary<string,string> ExampleFunction(Dictionary<string, string> dict)
        {
            return dict;
        }

        public static void CallingFunction()
        {
            ExampleFunction(new Dictionary<string, string>() { { "test", "test" } });
        }

在 C++ 中是否有等效的方法来执行此操作?如果在其他地方回答了这个问题,请原谅我——这似乎是一个基本问题,但我一定没有使用正确的搜索词。这最接近我想要的但没有雪茄:Creating a new object and passing in method parameter

【问题讨论】:

    标签: c++


    【解决方案1】:

    您可能正在寻找这样的东西:

    std::map<std::string, std::string> ExampleFunction(
        const std::map<std::string, std::string>& dict) {
      return dict;
    }
    
    void CallingFunction() {
      ExampleFunction({ { "test", "test" } });
    }
    

    Demo

    【讨论】:

    • 太好了,谢谢!我可以在执行 map> 时做类似的事情吗?我试过 map> test = {"Test", { { "test", "test" } } };并得到一个编译器错误,提示没有匹配的构造函数
    • 你的牙套太短了。 std::map&lt;std::string, std::map&lt;std::string, std::string&gt; &gt; test = { {"Test", { { "test", "test" } } } };
    • 啊,数字....再次感谢您的帮助。非常非常感谢。
    【解决方案2】:

    你可以这样做:

    #include <iostream>
    
    template<typename A, typename B> struct Dictionary
    {
        A Var1;
        B Var2;
    };
    
    template<typename A, typename B> Dictionary<A, B> func(Dictionary<A, B> dict)
    {
        return dict;
    }
    
    int main()
    {
        auto res = func(Dictionary<int, int>{123, 445});
        printf("%d - %d\n", res.Var1, res.Var2);
        getchar();
    
        return 0;
    }
    

    【讨论】:

    • 感谢您的评论! Map 更像是我的想法,但看到 Dictionary 实际以这种方式实现真是太酷了!
    猜你喜欢
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 2015-12-29
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多