views:

75

answers:

3

How can I perform endian conversion on vector of structs?

For example:

struct TestStruct
{
   int nSomeNumber;
   char sSomeString[512];
};

std::vector<TestStruct> vTestVector;

I know how to swap int values, but how to swap a whole vector of custom structs?

+2  A: 

As said in the comments. Endian swap each element in the vector:

auto iter = vTestVector.begin();
while( iter != vTestVector.end() )
{
    EndianSwap( iter->nSomeNumber );
    iter++;
}
Goz
A: 
#include <boost/foreach.hpp>

BOOST_FOREACH(TestStruct& s, vTestVector)
{
  SwapEndian(s.nSomeNumber);
}

Give or take, that'll do it. You don't need to affect the char string, just the numeric variable. s.

gbjbaanb
A: 

If you're looking for a general way to do this (i.e. a single piece of template metaprogramming code that would let you iterate over the elements of a plain struct, recursing into sub-structs and converting multibyte integer values whenever they are encountered) then you're out of luck. Unfortunately you can't iterate over elements of an arbitrary struct in C++ -- so you'll need to write special-case code for each different type.

j_random_hacker