0

I have a map like so:

std::map<LPCWSTR, LPCWSTR> myMap = {
    {L"key1", L"value1"},
    {L"key2", L"value2"}
};

And I need to get the value from a variable of type const wchar_t * that will match in value with the key. I tried

const wchar_t * key = L"key1";
wchar_t VALUE[350] = myMap[key];

but it tells me "initialization with '{...}' expected for aggregate object"

I also tried

wchar_t VALUE[350] = myMap.find(key)->second;

and I get the same build error In addition, I am adding this VALUE to another wchar_t using wcscat_s which is why I don't have too much leeway with variable types.

I'm pretty sure my map is set up correctly, so how can I get the value from a key?

Da Mahdi03
  • 1,468
  • 1
  • 9
  • 18
  • 2
    You can assign a pointer to a pointer, but not a pointer to an array. You need to use something like `wcscpy` which is the equivalent of `strcpy` for wide strings. Another perhaps better alternative is to use `std::wstring`. – Retired Ninja Jun 07 '21 at 01:32
  • from left you have array and from right - pointer. of course error. you can use `PCWSTR value = myMap[key];` you also can use `wcscpy_s` for make copy (are this need ?) `if (value = myMap[key]) wcscpy_s(VALUE, _countof(VALUE), value);` and this is pure *c++*, nothing related to *winapi* – RbMm Jun 07 '21 at 01:34
  • 3
    Also worth noting that using `LPCWSTR` as a key for the map and not providing a custom comparator is just a bad idea. Without the custom comparator the key uniqueness and sorting is based on the pointer value and not the data it points to. I'd personally use `std::wstring` as the key instead. You can read more here: https://stackoverflow.com/questions/4157687/using-char-as-a-key-in-stdmap – Retired Ninja Jun 07 '21 at 01:38
  • 1
    Just use `std::map` and don't look back. Putting raw pointers in a map is asking for trouble if the lifetime of the map outlives any of the pointers inside it. – selbie Jun 07 '21 at 02:51

1 Answers1

0

The value type in map is const wchar_t*, so you can assign it to a variable with the same type.Since c++11, we can use auto to deduce the type. Or use std::wstring if you want to copy the string.

All these assignment works

  const wchar_t* val = myMap[L"key1"];
  auto* val2 = myMap[L"key1"];
  LPCWSTR val3 = myMap[L"key1"];
  std::wstring str_val = myMap[L"key1"];

To copy the string into an array, you need to call wcsncpy. May like this:

  wchar_t VALUE[350];
  if (auto itr = myMap.find(L"key1"); itr != myMap.end()){
      wcsncpy(VALUE, itr->second, sizeof(VALUE)/ sizeof(VALUE[0]));
  }

It's error-prone and hard to maintain(The string's size may be larger than hardcoded 350, then only the front part of the string is copied), it's better to use std::wstring

Online demo

prehistoricpenguin
  • 6,130
  • 3
  • 25
  • 42