'C++ split std list into two lists
Hey so I'm reasonably new into c++ and I ran into this problem where I want to split one std list of strings into two lists.
For example: list(1,2,3,4) -> list1(1,2) & list2(3,4)
I guess splice is what I am supposed to use for this, but I could not understand how that works at all...
Can someone please advice me how to do this?
Sorry about my bad English and thanks for help everyone.
Solution 1:[1]
Try the following
#include <iostream>
#include <list>
#include <string>
#include <iterator>
int main()
{
std::list<std::string> lst1 = { "1", "2", "3", "4" };
for (const auto &s : lst1 ) std::cout << s << ' ';
std::cout << std::endl;
std::cout << std::endl;
std::list<std::string> lst2;
lst2.splice( lst2.begin(),
lst1,
lst1.begin(),
std::next( lst1.begin(), lst1.size() / 2 ) );
for (const auto &s : lst2 ) std::cout << s << ' ';
std::cout << std::endl;
for (const auto &s : lst1 ) std::cout << s << ' ';
std::cout << std::endl;
return 0;
}
The output is
1 2 3 4
1 2
3 4
The other approach
#include <iostream>
#include <list>
#include <string>
#include <iterator>
int main()
{
std::list<std::string> lst1 = { "1", "2", "3", "4" };
for (const auto &s : lst1 ) std::cout << s << ' ';
std::cout << std::endl;
auto middle = std::next( lst1.begin(), lst1.size() / 2 );
std::list<std::string> lst2( lst1.begin(), middle );
std::list<std::string> lst3( middle, lst1.end() );
for (const auto &s : lst2 ) std::cout << s << ' ';
std::cout << std::endl;
for (const auto &s : lst3 ) std::cout << s << ' ';
std::cout << std::endl;
return 0;
}
The output is
1 2 3 4
1 2
3 4
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
