-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.

0

2 Answers 2

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});
3
  • 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, 2018 at 7: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)); Jul 26, 2018 at 7:36
  • @RemyLebeau Good option for pre-c++11.
    – kocica
    Jul 26, 2018 at 7: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));

}

Not the answer you're looking for? Browse other questions tagged or ask your own question.