Re: How to encode STL vector
Re: How to encode STL vector
- Subject: Re: How to encode STL vector
- From: James Montgomerie <email@hidden>
- Date: Wed, 6 Nov 2002 19:38:00 -0800
On Wednesday, November 6, 2002, at 02:42 PM, Arthur Clemens wrote:
Thanks, this works. Only the archivers really don't like a vector with
no elements, so as a workaround I first tried to use conditionals: if
(size > 0)
but that gives another error when reading back in: "byte expected".
So I now always keep one element in the vector array. It's a bit
annoying.
...
You can encode it just like you would a plain C array:
//Encode
const unsigned size = myVector.size();
[aCoder encodeValueOfObjCType: @encode(unsigned) at: &size];
[aCoder encodeArrayOfObjCType: @encode(unsigned) count: size at:
&myVector.front()];
//Decode
unsigned size;
[aCoder decodeValueOfObjCType: @encode(unsigned) at: &size];
myVector.resize(size);
[aCoder decodeArrayOfObjCType: @encode(unsigned) count: size at:
&myVector.front()];
Note, however, that though in all the implementations I know of,
&myVector.front() does return an pointer to the Vector's internal
array, I don't believe it's guaranteed to by the standard. I think
that a Vector can use any O(1) storage, and if it did (or changed to in
the future) use something other than a plain array, your code would
break (because, for example, the second item is not guaranteed to be
adjacent in memory to the first).
More 'safe' would be to iterate through the Vector, saving out each
item separately, like this (warning, coding from memory, have not tried
to compile!). This would also solve your zero-element 'problem',
though it might make the resultant saved file rather larger:
//Encode
const unsigned size = myVector.size();
[aCoder encodeValueOfObjCType:@encode(unsigned) at:&size];
for(Vector<unsigned int>::iterator it = myVector.begin();
it!=myVector.end(); ++it) {
unsigned int value = *it;
[aCoder encodeValueOfObjCType:@encode(unsigned int) at:&value];
}
//Decode
unsigned size;
[aCoder decodeValueOfObjCType:@encode(unsigned) at:&size];
myVector.reserve(size);
for(int i =0; i < size; ++i) {
unsigned int value;
[aCoder decodeValueOfObjCType:@encode(unsigned int) at:&value];
myVector.push_back(value);
}
In practice it's probably nothing to worry about, but I thought that
someone should point it out.
Jamie.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.