Jump to content
  • Advertisement
Sign in to follow this  

STL Iterator Casting

This topic is 2554 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts


If anyone could help with this it would be appreciated.

I have an STL vector of chars, and an iterator pointing at a certain position. I need to cast the 4 bytes which are 8 bytes ahead of the iterator into an int, so I can assign to it - but I'm not sure of the syntax.

/* If it was a regular array, I could do: */
unsigned char buffer[500];
int index = some_value;
*(unsigned int*)&buffer[index + 8] = value;

/* I'm not sure of the syntax when using STL & iterators. */
std::vector<unsigned char> buffer;
std::vector<unsigned char>::iterator itr = buffer.begin();
*(unsigned int*)(*itr + 8) = value; /* I believe this adds eight to the value of the char, but something similar? */

It's actually for a stream cipher - I'm not just being obtuse :)

Thanks very much for any suggestions.

Share this post

Link to post
Share on other sites
I think the result is undefined due to potential alignment issues.

Original C code breaks just about every guarantee C++ and STL try to make. If doing that, might as well stick with C.

Otherwise, the C++ code is something like this:
std::vector<unsigned char> buffer;
std::vector<unsigned char>::iterator itr = buffer.begin();
std::advance(itr, 8);

for (int i = 0; i < 4; i++) { // hard-coded to 4 (or 8), since cypher doesn't care about 32/64 bits
*itr = (unsigned char) (value & 0xff); // should probably use a proper cast
value /= 256; // depends on the type of 'value'

Approximately. Untested.

Most of this is pointless, but there is a ton of gotchas.
- alignment requirements, on most non-x86 architectures writing to non-aligned address fails
- endianess - if just casting an int may result in different order (above is actually serialization problem)
- actually using iterators, instead of mangling pointers. Perhaps a non-issue in above case, but definitely not something iterators are for
If using raw pointers, memcpy would be *much* preferred to assigning to cast, but suffers from endianess issues.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!