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));
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
orstd::array
in astd::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:
Using the range constructor of the
std::forward_list
5std::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 tempstd::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.