Reputation: 563
I am reading Accelerated C++ and I need few suggestions on the question posted below.
What does this code do?
vector<int>u(10,100)
vector<int>v;
copy(u.begin(), u.end(), v.end());
Provide 2 possible ways to correct the program, and list its advantages and disadvantages.
The first part was pretty straightforward, but I need help in the second part. I have provided 3 approaches and I am wondering if there are any more possible solutions.
Also, I am not sure of advantages and disadvantages of my approach. I have made an attempt, so please give me your views.
copy()
std::vector<int> u(10, 100);
std::vector<int> v;
std::vector<int> w ;
std::vector<int> x ;
std::copy(u.begin(), u.end(), back_inserter(v)); // 1st way of doing
std::copy()
doesn't change the value of iteratorstd::copy()
don't depend on the specific container, the code can be reused with different containersstd::back_inserter()
only works with sequential containers and hence cannot be used with mapsstd::copy()
will not result in compiler errors but the program may behave differentlyinsert()
w.insert(w.end(), u.begin(), u.end() );
insert()
can be used with most containersCan't think of any.
push_back()
for ( std::vector<int>::const_iterator it = w.begin(); it != w.end(); ++it )
{
x.push_back( *it );
}
Cant think of any.
std::copy()
or vector::insert()
.Is my approach correct? What other possible solutions are there?
Upvotes: 3
Views: 899
Reputation: 1912
It seems to me, the authors mean std::copy() still should be used. So the first solution would be (as you suggested):
std::copy(u.begin(), u.end(), back_inserter(v));
Another one could be:
v.resize(u.size());
std::copy( u.begin(), u.end(), v.begin() );
Upvotes: 0
Reputation: 35449
Your title suggests that you're interested in copying a vector, but your code suggests you're interested in inserting into a vector (keeping in mind that despite its name std::copy
is used for insertion here).
If you want to copy:
// This requires the vector types to match exactly
std::vector<int> v = u;
// In case the vector differ in their value_type
// This requires that the value_type of the source be
// convertible to the value_type of the destination
std::vector<int> v(u.begin(), u.end());
If you want to insert, then both methods you describe (using std::copy
plus an iterator adaptor or calling the insert
member) are appropriate. You should pick one according to whether you're working with containers or with iterators in your particular spot of code. (When working with iterators the burden of using the iterator adaptor is put on the client that passes the iterator, so there's no need to worry about push_back
.) If all you have is iterators, then calling e.g. insert
is simply not an option; if you do have the containers and one of the members can do the job then feel free to use it. I would not consider an error to use an algorithm though.
Try to leave the explicit loop as a last resort option.
Upvotes: 5