vector of double[2] error

2019-07-15 02:00发布

问题:

why this error:

#include <vector>
typedef double point[2];

int main()
{
     std::vector<point> x;
}
/usr/include/c++/4.3/bits/stl_construct.h: In function ‘void std::_Destroy(_Tp*) [with _Tp = double [2]]’:
/usr/include/c++/4.3/bits/stl_construct.h:103:   instantiated from ‘void std::_Destroy(_ForwardIterator, _ForwardIterator) [with _ForwardIterator = double (*)[2]]’
/usr/include/c++/4.3/bits/stl_construct.h:128:   instantiated from ‘void std::_Destroy(_ForwardIterator, _ForwardIterator, std::allocator&) [with _ForwardIterator = double (*)[2], _Tp = double [2]]’
/usr/include/c++/4.3/bits/stl_vector.h:300:   instantiated from ‘std::vector::~vector() [with _Tp = double [2], _Alloc = std::allocator]’
prova.cpp:8:   instantiated from here
/usr/include/c++/4.3/bits/stl_construct.h:88: error: request for member ‘~double [2]’ in ‘* __pointer’, which is of non-class type ‘double [2]’

how to solve?

回答1:

You can't do that. As mentioned, arrays are not copyable or assignable which are requirements for std::vector. I would recommend this:

#include <vector>
struct point {
    double x;
    double y;
};

int main() {
     std::vector<point> v;
}

It will read better anyway since you can do things like:

put(v[0].x, v[0].y, value);

which makes it more obvious this the vector contains points (coordinates?)



回答2:

The only way you can solve this is to stop trying to do what you're trying to do. Arrays are not copyable or assignable.

In all honesty I didn't even know you could try to do something like this. It seems that the compiler is basically freaking the hell out. That doesn't surprise me. I don't know exactly why but I do know this will simply never work.

You should be able to, on the other hand, contain a boost::array without difficulty.

typedef boost::array<double,2> point;

You should look in the documentation to be sure I'm correct but I'm pretty sure this type is assignable and copy-constructable.



回答3:

Just to give an alternative solution, you can also use a pair of double:

#include <vector>
#include <utility>

typedef std::pair<double, double> point;

int main()
{
    std::vector<point> x;
    x.push_back(std::make_pair(3.0, 4.0));
}

But a struct or class named point is probably the best solution.



回答4:

I see no problem here. Perhaps an updated GCC (Glibc) would solve the problem?

    shade@vostro:~$ ls /usr/include/c++/
    4.4  4.4.3
    shade@vostro:~$ cd ~/Desktop
    shade@vostro:~/Desktop$ g++ test.cpp 
    shade@vostro:~/Desktop$ ./a.out 
    shade@vostro:~/Desktop$ 


回答5:

Use a struct or static array class like boost::array to contain the doubles.