3

I have been trying to create a map from integer to an array of bools. However, the following code does not seem to work.

map<int, bool[]> myMap;
bool one[] = {true, true, false};
myMap[1] = one;

I do not use array that much and there seems to be something seriously wrong here. Can someone point it out? Thanks in advance.

2
  • 2
    Instead of saying: "the code does not work" try telling us what the code does, and what you expected it to do. It helps us help you. Commented Sep 14, 2013 at 2:37
  • Arrays are not first class types in C++. You can't use it like that. You must use a pointer (or, even better, some proper container). Commented Sep 14, 2013 at 2:40

2 Answers 2

5

Storing an array like this in a map is not going to work, even if you could do it syntactically: the array is going to stay in the map even after the real array goes out of scope. Storing vectors of bool instead should work:

map<int, vector<bool> > myMap;
vector<bool> one {true, true, false}; // C++11 syntax
myMap[1] = one;
cout << myMap[1][0] << endl;
cout << myMap[1][1] << endl;
cout << myMap[1][2] << endl;

Here is a demo on ideone.

Sign up to request clarification or add additional context in comments.

Comments

3

With C++0x, you may write like this:

#include <iostream>
#include <map>
#include <array>

int main() {
    std::map<int, std::array<bool, 3>> maparr {
        {1, {true, false, true}}, 
        {2, {false, false, true}}};

    for(auto& item: maparr) {
        for (auto& val : item.second) {
            std::cout << val << ' ';
        }
        std::cout << std::endl;
    }
    return 0;
}

The output:

1 0 1

0 0 1

Since C++0x, we get a fixed size array.It may be what you are looking for.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.