-1

I need help using unsigned chars in std::vectors that are inside of a std::map.

This is how I declare the std::map:

std::map<int, std::vector<unsigned char>> DataMap;

The problem comes when I try to assign a std::vector to the std::map.

it->first comes from another std::map, as this code is inside a loop.

std::vector<unsigned char> charHolder;
for(int i = 0; i < 10; i++)
{
    charHolder.push_back('2');
}

DataMap.insert(std::pair<int, std::vector<unsigned char>(it->first, charHolder));

The errors:

Template argument 2 is invalid

I need to assigned a char[] array to the 2 place in the std::map. I've tried an array, but I had no luck.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
JackCross
  • 37
  • 5

2 Answers2

1

You are missing a > character

DataMap.insert (std::pair<int, std::vector<unsigned char>>(it->first, charHolder));
                                                         ^

You may use uniform initializer as following:

DataMap.insert ({it->first, charHolder});
kocica
  • 6,412
  • 2
  • 14
  • 35
  • 1
    It's always best to have someone look over your work, but unfortunately I don't have that so thanks for the help :) – JackCross Jul 26 '18 at 07:07
  • 1
    Another option, especially for pre-C++11 compilers, is to use `std::make_pair()` instead and let the compiler deduce the template parameters for you: `DataMap.insert(std::make_pair(it->first, charHolder));` – Remy Lebeau Jul 26 '18 at 07:36
  • @RemyLebeau Good option for pre-c++11. – kocica Jul 26 '18 at 07:40
0

Some of the many fun and varied ways to get data into a map:

std::map<int, std::vector<unsigned char>> DataMap;

void add(int i, std::vector<unsigned char> v)
{
    // efficient move versions
    DataMap.emplace(i, std::move(v));

    DataMap[i] = std::move(v);

    DataMap.insert(std::make_pair(i, std::move(v)));

    DataMap.emplace(std::piecewise_construct, 
        std::make_tuple(i), 
        std::forward_as_tuple(std::move(v)));

    // less efficient copy versions
    DataMap.emplace(i, v);

    DataMap[i] = v;

    DataMap.insert(std::make_pair(i, v));

    DataMap.emplace(std::piecewise_construct, 
        std::make_tuple(i), 
        std::make_tuple(v));

}
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142