0

In C#, I could so something like the following:

        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.

ww2406
  • 109
  • 9

2 Answers2

1

You may be looking for something like this:

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

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

Demo

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
  • That's great, thanks! Can I do something similar when doing a map >? I've tried map > test = {"Test", { { "test", "test" } } }; and get a compiler error that says no matching constructor – ww2406 May 18 '20 at 01:27
  • 1
    You are a pair of braces short. `std::map > test = { {"Test", { { "test", "test" } } } };` – Igor Tandetnik May 18 '20 at 01:31
  • Ah, figures....thanks again for your help. Much, much appreciated. – ww2406 May 18 '20 at 01:47
1

you can do that like this:

#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;
}
tb044491
  • 144
  • 7
  • Thanks for your comment! Map was more what I had in mind, but this is cool to see Dictionary actually implemented this way! – ww2406 May 18 '20 at 01:48