Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 853
Dhruv Avatar asked Jan 21 '26 22:01

Dhruv


1 Answers

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.

like image 134
JeJo Avatar answered Jan 23 '26 18:01

JeJo