Skip to main content

C++ STL Forward List Container – std::forward_list

In this tutorial you will learn about C++ STL forward list i.e., std::forward_list and operations, methods applicable on it.

Forward Lists come under sequence containers. Forward List implements singly linked list. Insertion, removal and moving operations are very fast than other containers. Every element of forward list contains its next element address. Main disadvantage of forward list is that cannot be iterated backwards and its individual elements cannot be accessed directly. When singly linked list preferred over double linked list, Forward list is better than List. Because list behaves a like double linked list. Example for where we can use forward list is chaining in hashing, adjacency list representation of graph etc.

Also Read: C++ STL List Container – std::list

C++ STL Forward List

Now let’s see what are the operations we can apply on forward list:

assign(): Just like insert method, assign() will store the values. By using assign() we can insert elements in two ways.

First way is we can insert what are the elements we required. Second way is we can insert a single element “n” number of times. But in second way of assignment list will be replaced by new values. Old list values will be erased.

Try this below code for more understanding:

#include<iostream>
#include<forward_list>

using namespace std;

int main(){
    forward_list<int> lst1; // declaration of a list
    forward_list<int> :: iterator it; // iterator for list

    // assigning values into list.
    lst1.assign({10,20,30});

    for(it = lst1.begin(); it!= lst1.end(); ++it)
        cout << *it << " ";
    
    cout << endl;

    // using assign() method in other way
    lst1.assign(3,99);
    // assigning three elements of each value 99
    
    for(it = lst1.begin(); it!= lst1.end(); ++it)
        cout << *it << " ";
    
    cout << endl;
    
    return 0;
}

Output

10 20 30
99 99 99

Insert Functions

push_front(): This function used to insert new value at beginning of the list. The value from this function copied to the address before to the current first element of container.

emplace_front(): This function also used to insert elements at beginning of the container but there no copy operation. Here element directly inserts at the address before to the first element.

insert_after(): Using this function we can insert element at any position of the forward list. The arguments which we pass to this function will be copied to particular location.

emplace_after(): This also works same as insert_after() function. But element directly insert without any copy operation.

Example program to show above insert functions:

#include<iostream>
#include<forward_list>

using namespace std;

int main(){
    forward_list <int> lst1;
    forward_list <int> :: iterator it;
    forward_list <int> :: iterator it1;
    
    lst1.assign({10,20,30}); // initially these 3 values are in forward list

    // using push front method
    lst1.push_front(5);

    // using emplace_front to insert at front
    lst1.emplace_front(4);

    // check the result
    for(it= lst1.begin(); it!= lst1.end(); ++it)
        cout << *it << " ";
    
    cout << endl;

    // using insert_after function
    it1 = lst1.insert_after(lst1.begin(),99); // inserting 99 after current first element

    // using emplace_after function
    lst1.emplace_after(it1,0); // inserting 0 after which it1 iterator pointing to.

    // checking the result
    for(it = lst1.begin(); it!= lst1.end(); it++)
        cout << *it << " ";
    
    cout << endl;

    return 0;
}

Output

4 5 10 20 30
4 99 0 5 10 20 30

Delete Functions

pop_front(): This function removes the first element of the forward list.

erase_after(): This function used to delete the element at particular position of forward list.

remove(): This function removes the specific element which we pass as an argument to this function

remove_if(): This function removes the element we specified only the condition which we gives is true.

Example program to show above erasing functions of forward list:

#include<iostream>
#include<forward_list>

using namespace std;

int main(){
    forward_list <int> lst1;
    forward_list <int> :: iterator it;

    lst1.assign({10,20,30,40,50});
    // initially we assigned some values into forward list

    // deleting first element
    lst1.pop_front();

    // deleting element at particular position using erase after function
    it = lst1.begin();
    lst1.erase_after(it);

    // check the result
    for(it = lst1.begin(); it!= lst1.end(); ++it)
        cout << *it << " ";
    
    cout << endl;

    // deleting an element using remove function
    lst1.remove(50); // removing element 50 in forward list

    // deleting element by condition
    lst1.remove_if([](int a){ return a>25;});

    // check the result
    for(it = lst1.begin(); it!= lst1.end(); ++it)
        cout << *it << " ";
    
    cout << endl;
    
    return 0;
}

Output

20 40 50
20

Some more functions are:

splice_after(): This function used to transfer one forward list elements to other forward list. It places the elements after specified position only.

reverse(): This function reverse all elements of the forward list.

sort(): This function sorts the elements in the forward list.

Example program to explain above functions:

#include<iostream>
#include<forward_list>

using namespace std;

int main(){
    forward_list <int> lst1;
    forward_list <int> lst2;
    forward_list <int> :: iterator it;
    
    lst1.assign({20,40,60});
    lst2.assign({30,50,70});

    // now adding forward list1 elements to forward list2 using splice_after function after first element in this list
    lst2.splice_after(lst2.begin(),lst1);

    // Checking after adding forward list1 to forward list2
    cout << "after adding forward list1 into forward list2" << endl;
    for (it= lst2.begin(); it!= lst2.end(); ++it)
        cout << *it << " ";
    
    cout << endl;

    lst2.reverse(); // preforming reverse operation on forward list2

    // printing revere elements
    cout << "after reversing forward list2" << endl;
    for (it= lst2.begin(); it!= lst2.end(); ++it)
        cout << *it << " ";
   
    cout << endl;

    // sorting elements
    lst2.sort();
    cout << "after sorting the elements" << endl;
    for (it= lst2.begin(); it!= lst2.end(); ++it)
        cout << *it << " ";
    
    cout << endl;
    
    return 0;
}

Output

after adding forward list1 into forward list2
30 20 40 60 50 70
after reversing forward list2
70 50 60 40 20 30
after sorting the elements
20 30 40 50 60 70

Comment below if you have queries or found any information incorrect in above tutorial for C++ STL forward list.

The post C++ STL Forward List Container – std::forward_list appeared first on The Crazy Programmer.



from The Crazy Programmer http://www.thecrazyprogrammer.com/2017/08/stl-forward-list.html

Comments

Popular posts from this blog

dotnet sdk list and dotnet sdk latest

Can someone make .NET Core better with a simple global command? Fanie Reynders did and he did it in a simple and elegant way. I'm envious, in fact, because I spec'ed this exact thing out in a meeting a few months ago but I could have just done it like he did and I would have used fewer keystrokes! Last year when .NET Core was just getting started, there was a "DNVM" helper command that you could use to simplify dealing with multiple versions of the .NET SDK on one machine. Later, rather than 'switching global SDK versions,' switching was simplified to be handled on a folder by folder basis. That meant that if you had a project in a folder with no global.json that pinned the SDK version, your project would use the latest installed version. If you liked, you could create a global.json file and pin your project's folder to a specific version. Great, but I would constantly have to google to remember the format for the global.json file, and I'd constan...

15 Web Design Trends to Watch in 2018

The modern world is full of extraordinary things that influence our imagination and mood. Our soul needs a perfect atmosphere and impressive spots. To apply such things in practice, we have submitted the list of the web trends that deserve your attention. Robert frost design analysis will meet all your wishes and expectations. Image Source Web Design Trends to Watch in 2018 1. More Organic Shapes Until this year, web design, as well as mobile design, were based on the right-angled and sharp-edged shapes. However, it seems that this year will bring some significant changes in the field of web design. The recent trends will offer the absolute rounded corners. In addition, the web design of 2018 will make the real things look like the cartoonish ones. 2.   Bold Minimalism Although some of you may think that this web design trend will not attract the Internet users. Indeed, the notion of minimalism is often associated with boredom and dullness. However, in this case, bold ...

R vs Python for Machine Learning

There are so many things to learn before to choose which language is good for Machine Learning. We will discuss each and everything about R as well as Python and the situation or problem in which situation we have to use which language. Let’s start Python and R are the two most Commonly used Programming Languages for Machine Learning and because of the popularity of both the languages Novice or you can say fresher are getting confused, whether they should choose R or Python language to commence their career in the Machine learning domain. Don’t worry guys through this article we will discuss R vs Python for Machine Learning. So, without exaggerating this article let’s get started. We will start it from the very Basics things or definitions. R vs Python for Machine Learning Introduction R is a programming language made by statisticians and data miners for statistical analysis and graphics supported by R foundation for statistical computing. R also provides high-quality graphics and...