how would you transfer members of an array to a vector.
4 Answers
You can initialize it with the vector constructor that takes two iterators, like this:
std::vector<chair> points(chairarray, chairarray + arraysize);
As a member of your house class, you would do that in the initialization list:
house::house(int arraysize, chair* chairarray)
:points(chairarray, chairarray + arraysize)
{}
2 Comments
chairarray up to but not including that point. It's analogous to what std::vector::end returns (or any container's end member function, for that matter).I would probably use something like the following:
points.insert(points.end(), chairarray, chairarray + arraysize);
(This is making an assumption that the elements of chairarray and the elements of points is the same.)
You are likely segfaulting because you are trying to modify members of points that do not yet exist. You can't, for example, set points[0] if the current size of points is zero.
Comments
Firstly, the segment fault issue, just as @md5i had mentioned, the statement std::vector<chair> points; was to initialize points with default constructor, so the size is zero.
there are 4 methods for vectorcontainer to initialize object, here are some code snippet form STL source:
explicit vector(const allocator_type& __a = allocator_type())
: _Base(__a) {}
vector(size_type __n, const _Tp& __value,
const allocator_type& __a = allocator_type())
: _Base(__n, __a)
{ _M_finish = uninitialized_fill_n(_M_start, __n, __value); }
explicit vector(size_type __n)
: _Base(__n, allocator_type())
{ _M_finish = uninitialized_fill_n(_M_start, __n, _Tp()); }
vector(const vector<_Tp, _Alloc>& __x)
: _Base(__x.size(), __x.get_allocator())
{ _M_finish = uninitialized_copy(__x.begin(), __x.end(), _M_start); }
what @Benjamin Lindley used was the last one, and points.insert(points.end(), chairarray, chairarray + arraysize); was one method in vector, so many ways to tackle your main question about "initialize vector from array" :)
Comments
You need to allocate elements in points first. Just add one line:
house::house(int arraysize, chair* chairarray)
{
points.resize(arraysize); // add this
for(int i=0; i<arraysize; ++i)
{
points[i].x=chairarray[i].x;
points[i].y=chairarray[i].y;
}
}
Generic copy can also save you lots of typing:
points.resize(arraysize);
std::copy(chairarray, chairarray+arraysize, points.begin());
points.int values[] = {1, 2 ,3}; std::vector<int> copies(std::begin(values), std::end(values));