Skip to content

Instantly share code, notes, and snippets.

@odarbelaeze
Created June 26, 2013 13:43
Show Gist options
  • Save odarbelaeze/5867459 to your computer and use it in GitHub Desktop.
Save odarbelaeze/5867459 to your computer and use it in GitHub Desktop.
Using std::copy to cast between container types with c++11.
#include <algorithm>
#include <iostream>
#include <valarray>
#include <vector>
template<typename T>
std::ostream& operator<< (std::ostream& os, std::valarray<T> va)
{
for (auto&& i : va)
os << i << " ";
return os;
}
int main(int argc, char const *argv[])
{
std::initializer_list<double> a{1, 2, 3};
std::valarray<int> b(a.size());
std::copy(begin(a), end(a), begin(b));
// std::cout << a << std::endl;
std::cout << b << std::endl;
// The only thing you really need to worry about is the
// target contaniner to have enough space to store all the
// values, for example, this will result in a segmentation fault
// std::vector<int> v{2, 3, 4};
// std::valarray<double> c();
// std::copy(begin(v), end(v), begin(c));
// because the std::valarray has no allocated space.
std::vector<int> v{2, 3, 4};
std::valarray<double> c(v.size());
std::copy(begin(v), end(v), begin(c));
std::cout << c << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment