Re: Is CArray best for this...
David Ching wrote:
Thanks G, the C# sample is really ideal, isn't it? I mean look at the "STL
overhead" that is completely absent from C#:
typedef
std::
StringMap::const_iterator
.begin
.end
++it
.first // <-- this is how to access "key"; really bizarre
That's what I meant when I say STL appeals to computer scientists, as they
manage to throw in all manner of extraneous technical gobbly-gook to
accomplish the simplest things.
I also don't like STL behavior that if the element you reference has a
default constructor, referencing the element creates it behind your back,
and if it doesn't have a default constructor, an exception is thrown.
Having different behavior like this is definitely not treating the data type
as a simple extension to the C style [] array and creates errors.
David:
I thought we were comparing the STL with the MFC collection classes. I don't
think CMap is any simpler here, and the concepts you list above are either
standard C++ or common to the entire STL.
In your last paragraph, std::vector does not have this "behind your back" feature.
Rather, I think you are talking about std::map::operator[](), but what you say
is not true. If you use this operator in your code, the VALUE class must have a
default constructor, or the code will not compile, so no exception can be thrown
if you try to access a non-existent element. If you do not use this operator you
do not need a default constructor.
For some reason, you cannot compile a CMap at all if the value type does not
have a default constructor. But if you do have such a constructor then the (VC9)
documentation for CMap is very confusing:
---------------------------------
VALUE& operator[](
ARG_KEY key
);
<snip>
Remarks
Thus (sic) it can be used only on the left side of an assignment statement (an
l-value). If there is no map element with the specified key, then a new element
is created.
There is no "right side" (r-value) equivalent to this operator because there is
a possibility that a key may not be found in the map. Use the Lookup member
function for element retrieval.
------------------------------
This is nonsense. There is nothing in the C++ language to prevent the above
operator from being used as a r-value. Indeed the following code runs cleanly:
typedef CMap<int, const int&, int, const int&> IntMap;
IntMap intMap
int n = intMap[0]; // doesn't exist
ASSERT (n == 0);
ASSERT (intMap.GetSize() == 1);
as does the analogous code for std::map.
You may not like this back-door insertion of elements into the map, but there is
really no difference between CMap and std::map in this regard.
--
David Wilkinson
Visual C++ MVP