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 ?
I want to know that, is there a way to add a
std::vectororstd::arrayin astd::forward_listwithout any loop?
Since the question is more generic, I would like to give all the possible solutions using std::forward_list itself:
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() };
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() };
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 }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With