Question

I guess this question is building on C++ convert vector<int> to vector<double>

I am trying to cast a two dimensional vector (stored in an object) of type int into a two dimensional vector of type double. According to the SO link I have provided,

std::vector<int> intvec;
std::vector<double> doubvec(intvec.begin(),intvec.end());

should typecast the original vector (it does).

So why doesn't the following code work?

std::vector<std::vector<double>> rotmat(Mesh.matrix.begin(),Mesh.matrix.end());

I can do the line below just fine, so I know there isn't anything else wrong. What am I missing?

std::vector<double> dubvec(Mesh.matrix[0].begin(), Mesh.matrix[0].end());

Mesh is defined by :

class MeshOut
{
public:

MeshOut();



MeshOut(vector < vector < int >>, vector < vector < int >>, int, int, double, int, bool);

vector<vector<int>> matrix;
vector<vector<int>> lv_mat;
int shortNum;
int SourceNum;
double smallestMeshSize;
int factor;
bool Fine;
....

I call Meshout Mesh(x,y,z,i,j,k,l); in the code.

Was it helpful?

Solution

While there is an implicit conversion rule between the primitive int and double types, there is non between std::vector<int> and std::vector<double>.

In fact, there is no relation between those two types from a class hierarchy perspective.

OTHER TIPS

Short answer: use a loop and get on with it ;-P

Long answer: you could avoid the loop if you go well out of your way to do so.

The vector constructor you're using takes a pair of iterators: as it iterates, it basically populates the vector with successive element_type(*iterator)s, so the element_type need to be constructed from a single dereferenced iterator value. To construct a vector<vector<double>>, the iterators need to yields values from which vector<double>s can be implicitly constructed. Per cppreference vector docs, the potentially useful constructors are:

  • vector(const vector&)

  • vector(vector&&)

  • vector(std::initializer_list<T> init, const Allocator& = Allocator())

Of these, the first two need pre-existing vector<double> objects, but the last is a little more interesting. As your Mesh is a user-defined type, and you create an iterator type that when dereferenced produces std::initializer_list<double> objects sliced from successive vector<int> in .matrix, then you could support the vector<vector<double>> construction syntax you tried. The std::initializer_list<T>s are then effectively temporaries that may not be able to be optimised away, but the same is true if you copy std::vector<double> around after using a single explicit loop. If you really care about efficiency, profile and compare with having nested loops using reserve and push_back....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top