views:

174

answers:

4

I used in my C++/CLI project static array's like:

static array < array< String^>^>^ myarray=
{
  {"StringA"},
  {"StringB"}
};

Is it possible to create a dictionary the same way? I was not able to create and initialize one.

static Dictionary< String^, String^>^ myDic=
{
  {"StringA", "1"},
  {"StringB", "2"}
};

Thx

A: 

I don't know about CLI but shouldn't a two dimensional array get pretty close to what you want?

#include <iostream>

int main() {
  static int a[][3] = { {1, 2, 3}, {4, 5, 6}};
  std::cout << a[0][0] << " " << a[1][0];
  //..

}
pmr
+1  A: 

Your Dictionary example, and others, are called a Collection Initializer in C#.

You can't do it in C++/CLI.

// C# 3.0
class Program
{
    static Dictionary<int, string> dict = new Dictionary<int, string>
    {
        {1, "hello"},
        {2, "goodbye"}
    };

    static void Main(string[] args)
    {
    }
}
frou
A: 

You can't do it at the point of the declaration, but you could use a static constrictor to do one time initialization via use of the Add() method.

GBegen
A: 

Although in C++ you can't create an std::map and initialize it like an array, you can load the map upon construction using this constructor:

template <class InputIterator>
  map ( InputIterator first, InputIterator last,
        const Compare& comp = Compare(), const Allocator& = Allocator() );

One alternative is to use an array and a search method, such as binary_search. This may be useful if the data does not change.

Thomas Matthews