I want to do something like this:

unsigned char r[3] = {255, 0, 0};
map<unsigned char[3], int> ColorList;
ColorList[r] = 1;

But I get the following:
error: array used as initializer

How else would I set the r element of the map?

Thanks,

Dave

Recommended Answers

All 4 Replies

Well, since arrays deteriorate into pointers to the first element, you could go with:

map<unsigned char*, int> ColorList;

If you use this code though, the map will end up containing invalid pointers unless the lifetime of of the array(s) and the lifetime of the map are the same. Also, the maps comparator function won't work how you want it to, since it will perform pointer compares.

Solutions? Either:
- make a class "Color" which contains the rgb array, and overide operator< ( since this is what a map uses for its ordering ).
- use an std::basic_string<unsigned char> to represent the colour, (if you don't mind the fact that it doesn't have a fixed size).
- use an std::pair<uchar,std::pair<uchar,uchar>> (although that's ugly).
- write a generalized 3-tuple (triple) class, or even a fully generalized (arbitrary sized) tuple class.
- concatenate the uchar elements (by left-shift and binary-or, or by using a non-portable union/cast trick) into a single (32-bit) int, and you have 8bits left over for alpha, and the < comparator is then free, and very fast.

Willing to further explain any of those methods, if necessary.

wow, thanks for the options. Someone else suggested I just use
map<vector<unsigned char>, int> ColorList;

Is that a bad idea? It seems like less work, but I didn't see it listed in your plethora of suggestions haha.

Thanks,

Dave

That's pretty much the same as using an std::basic_string<uchar>; the only reason I didn't suggest it because I wasn't sure off the top of my head whether std::vector<T> provides a useful implementation of operator<.. but, a quick check reveals that it does (it's a lexicographic compare, just like std::basic_string<T> ), so that'll work just as well.

awesome - thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.