claire.bell1 <cl**********@ntlworld.com> wrote in message
news:cl*******************@newsfep2-win.server.ntli.net...
Hi,
Im having lots of problems trying to implement a vector of arrays in C++.
I'm not surprised. Containers require that the elements they
contain be copyable and assignable. Arrays do not meet this
requirement. You're already using a container (vector), so
why are you using an array? How about a vector of vectors?
Im trying to make a vector that will hold coordinates. Ive decided to
implement a coordinate as an array of integers of length 2.
IMO a poor decision. Either create a 'coordinate' type (class),
or if you only need 'raw' storage for two values, use a 'std::pair'
My code to initialise this array is:
vector<int[2]> coordVector;
This seems to compile ok but im not sure if it is making a vector of
arrays because the command:
coordVector.push_back({0,0}) does not work.
(If it were allowed) the element type is 'int[2]', so
'push_back()'s argument must be this type or a type
convertible to it. {0, 0} is not a valid expression
except as an array initializer. It certainly does
not have type 'int[2]'.
Im sure im just doing something simple wrong
Yes, you're trying to store noncopyable, nonassignable
items in a container.
but im having a nightmare
trying to fix it.
As long as you continue to try to break the language
rules, the nightmares will continue.
Does anyone have any example code that uses a vector of
arrays that i could look at?
Nope, because that's illegal.
Try:
#include <iostream>
#include <ostream>
#include <utility>
#include <vector>
typedef std::pair<int, int> coord_t;
typedef std::vector<coord_t> coord_list_t;
std::ostream& operator<<(std::ostream& os,
const coord_t& coord)
{
return os << coord.first << ", " << coord.second;
}
std::ostream& operator<<(std::ostream& os,
const coord_list_t& lst)
{
for(coord_list_t::size_type i = 0; i != lst.size(); ++i)
os << lst[i] << '\n';
return os;
}
int main()
{
coord_list_t coordVector;
coordVector.push_back(coord_t( 0, 0));
coordVector.push_back(coord_t(42, 25));
coordVector.push_back(coord_t(18, 69));
std::cout << coordVector << '\n';
return 0;
}
BTW which C++ book(s) are you reading? Perhaps you
need better ones.
-Mike