我可以即时创建新地图并作为函数参数传递吗?

在C#中,我可以像下面这样:

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

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

Is there an equivalent way to do this in C++? Forgive me if this is answered elsewhere--this seems like a basic question, but I must not be using the right search terms. This comes closest to what I was looking for but no cigar: Creating a new object and passing in method parameter.

评论
raut
raut

您可以这样做:

#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;
}
点赞
评论
劫走EXO
劫走EXO

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

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

void CallingFunction() {
  ExampleFunction({ { "test", "test" } });
}

Demo

点赞
评论