Home > Enterprise >  How to insert std::vector or array to a std::forward_list without using any loop?
How to insert std::vector or array to a std::forward_list without using any loop?

Time:10-02

forward_list<int> listOne;
forward_list<int> listTwo;
vector<int> arr = {2,4,3};
forward_list<int>::iterator it;

In the code mention above, I want to insert a std::vector in listOne and I tried using insert_after function.


it = listOne.begin();
listOne.insert_after(it,arr);

But it didn't work.

I want to know that, is there a way to add a std::vector or array in a std::forward_list without any loop ?

CodePudding user response:

You could use a std::copy with std::front_inserter

copy(arr.rbegin(), arr.rend(), front_inserter(listOne));

Working demo

CodePudding user response:

If you need it on construction you can pass begin() and end() iterators to the forward_list constructor:

std::vector<int> vec{1, 2, 3, 4, 5, 6};
std::forward_list<int> list{vec.cbegin(), vec.cend()};

CodePudding user response:

I want to know that, is there a way to add a std::vector or std::array in a std::forward_list without any loop?

Since the question is more generic, I would like to give all the possible solutions using std::forward_list itself:

  1. Using the range constructor of the std::forward_list5

    std::vector<int> arr{ 1, 2, 4, 3 };
    std::forward_list<int> listOne{ arr.cbegin(), arr.cend() };
    
  2. Using the assignment std::forward_list::operator=3 (creates a temp std::initializer_list from range passed)!

    std::vector<int> arr{ 1, 2, 4, 3 };
    std::forward_list<int> listOne = { arr.cbegin(), arr.cend() };
    
  3. To replaces the contents of the forward_list, via member std::forward_list::assign()

    std::vector<int> arr{ 1, 2, 4, 3 };
    std::forward_list <int> listOne{ 11, 22 };
    listOne.assign(arr.cbegin(), arr.cend());  // replaces the  { 11, 22 }
    
  4. To inserts elements after the specified position in the forward list via the member std::forward_list::insert_after()

    std::vector<int> arr{ 1, 2, 4, 3 };
    std::forward_list <int> listOne{ 0 };
    // insert the arr after the first element
    listOne.insert_after(listOne.begin(), arr.cbegin(), arr.cend()); 
    

Here is a demo of above all.

  • Related