Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use std::back_inserter instead of end() during std::copy?

Tags:

c++

I have seen std::copy() using std::back_inserter but I used std::end() and both works. My question is, why was std::back_inserter needed if std::end() does the works just fine?

#include <iostream> 
#include <iterator> 
#include <vector> 
#include <algorithm> 
using namespace std; 

int main() 
{ 
    // Declaring first container 
    vector<int> v1 = { 1, 2, 3 }; 

    // Declaring second container for 
    // copying values 
    vector<int> v2 = { 4, 5, 6 }; 

    // Using std::back_inserter inside std::copy 
    //std::copy(v1.begin(), v1.end(), std::back_inserter(v2));  // works
    std::copy(v1.begin(), v1.end(), v2.end());  // also works
    // v2 now contains 4 5 6 1 2 3 

    // Displaying v1 and v2 
    cout << "v1 = "; 

    int i; 
    for (i = 0; i < 3; ++i) { 
        cout << v1[i] << " "; 
    } 

    cout << "\nv2 = "; 
    for (i = 0; i < 6; ++i) { 
        cout << v2[i] << " "; 
    } 

    return 0; 
}
like image 213
mato Avatar asked Jan 21 '19 20:01

mato


People also ask

What is std :: Back_inserter?

std::back_inserter in C++ A back-insert iterator is a special type of output iterator designed to allow algorithms that usually overwrite elements (such as copy) to instead insert new elements automatically at the end of the container.

When to use std:: copy?

C++ STL std::copy() function copy() function is a library function of algorithm header, it is used to copy the elements of a container, it copies the elements of a container from given range to another container from a given beginning position.

Why use back_ inserter c++?

The back_inserter method in C++ is used to construct an iterator, which holds the responsibility of inserting new elements to the end of the “x” or the container, with which the method is applied, and this method is defined within the header file of the program.

How does Back_inserter work?

back_inserter() returns a back_insert_iterator , which has to function like an output iterator. Specifically, it has to support operations such as pre- and post increment, and dereference assignment. If it didn't support those operations, it couldn't be used where output iterators are required.


1 Answers

The first one inserts values into the vector, the other one is undefined behavior, it writes items into the spot just past the end of the vector.

Try printing the resulting vector:

std::copy(v1.begin(), v1.end(), std::back_inserter(v2));  // works
for (auto x : v2) cout << " " << x;
cout << endl;

Prints

 4 5 6 1 2 3

Whereas

std::copy(v1.begin(), v1.end(), v2.end());
for (auto x : v2) cout << " " << x;
cout << endl;

Prints

 4 5 6

(In Debug mode raises an assertion failure)

The fact that it works for you in your particular compiler doesn't make it correct. Appearing to work is a typical manifestation of UB.

like image 139
rustyx Avatar answered Dec 28 '22 02:12

rustyx