The correct way to work with vector arrays

Can anyone say what is the correct way to work with an array vector?

I declared a vector of arrays ( vector<float[4]> ), but got error: conversion from 'int' to non-scalar type 'float [4]' requested when trying to resize it. What is going wrong?

+47
c ++ arrays vector stdvector
Jan 06 '11 at 6:11
source share
4 answers

You cannot store arrays in vector or any other container. The type of elements to be stored in the container (called the container's value type) must be both constructive and assignable. Arrays are also not.

However, you can use an array class template such as the one provided by Boost, TR1, and C ++ 0x:

 std::vector<std::array<double, 4> > 

(You want to replace std::array with std::tr1::array to use the template included in C ++ TR1, or boost::array to use the template from the Boost library . Alternatively, you can write your own, it's pretty simple.)

+96
Jan 6 '11 at 6:18
source share

Using:

 vector<vector<float>> vecArray; //both dimensions are open! 
+7
Jan 06 '11 at 6:15
source share

There is no error in the following code snippet:

 float arr[4]; arr[0] = 6.28; arr[1] = 2.50; arr[2] = 9.73; arr[3] = 4.364; std::vector<float*> vec = std::vector<float*>(); vec.push_back(arr); float* ptr = vec.front(); for (int i = 0; i < 3; i++) printf("%g\n", ptr[i]); 

EXIT:

6.28

2,5

9.73

4,364

IN CUSTODY:

 std::vector<double*> 

- another opportunity besides

 std::vector<std::array<double, 4>> 

which was proposed by James McNellis.

+7
Oct 06 '14 at 11:37
source share

Each element of your vector is a float[4] , so when resizing, each element must be initialized by default from float[4] . I suppose you tried to initialize an int value like 0 ?

Try:

 static float zeros[4] = {0.0, 0.0, 0.0, 0.0}; myvector.resize(newsize, zeros); 
+5
Jan 06 '11 at 6:17
source share



All Articles