If you just want to convert from one type to the other then use the standard constructor. As long as the iterators value type is auto convertible to the destination vectors value type the compiler will do the auto conversion between the two types. Just use the standard constructor
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<unsigned char> a;
a.push_back((unsigned char)12);
a.push_back((unsigned char)13);
a.push_back((unsigned char)14);
std::vector<unsigned short> b(a.begin(),a.end());
// Print out the vector
std::copy(b.begin(),b.end(),std::ostream_iterator<unsigned short>(std::cout,"\t"));
}
> g++ t.cpp
> ./a.out
12 13 14
If you actually want to convert two bytes into one then some work is required. But it depends if the input data is actually the same endianess as the machine you are on. If you know that it is the same endianess that you just need to cast the input type.
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<unsigned char> a;
// Make sure that the size is correct.
// ie. An Odd number indicates that something is not quite correct.
//
std::vector<unsigned short> b(static_cast<unsigned short*>(&a[0]),
static_cast<unsigned short*>(&a[a.size()]));
// Print out the vector
std::copy(b.begin(),b.end(),std::ostream_iterator<unsigned short>(std::cout,"\t"));
}
Alternatively if you actually need to combine two values into a single value where the endianess is not the same as the target architecture, you can write a special iterator. Something like this:
#include <Converter.h>
int main()
{
std::vector<unsigned char> a;
// Make sure that the size is correct.
// ie. An Odd number indicates that something is not quite correct.
//
std::vector<unsigned short> b(make_Converter(a.begin()),make_Converter(a.end()));
// Print out the vector
std::copy(b.begin(),b.end(),std::ostream_iterator<unsigned short>(std::cout,"\t"));
}
Converter.h
#include <vector>
#include <iostream>
#include <iterator>
template<typename I>
struct Converter
{
I iterator;
typedef typename std::input_iterator_tag iterator_category;
typedef typename std::iterator_traits<I>::value_type value_type;
typedef typename std::iterator_traits<I>::difference_type difference_type;
typedef typename std::iterator_traits<I>::pointer pointer;
typedef typename std::iterator_traits<I>::reference reference;
Converter(I iter)
:iterator(iter)
{}
Converter& operator++()
{
iterator++;
return *this;
}
Converter operator++(int)
{
Converter tmp(*this);
this->operator++();
return (tmp);
}
value_type operator*()
{
/*
* The actual calculation done here will depend on the underlying hardware.
*/
typename std::iterator_traits<I>::value_type val(*iterator);
val << 8;
iterator++;
val |= (*iterator);
return val;
}
bool operator!=(Converter const& rhs)
{
return iterator != rhs.iterator;
}
};
template<typename I>
Converter<I> make_Converter(I iter)
{
return Converter<I>(iter);
}