forward_list question

Hi all,

I have a series of commands as follows:

1
2
3
Append 2
Append 3
Prepend 1


The requirement is to use STL forward_list to create those commands in main.
The hint here is that it only needs 4 lines of code to do them.

However, forward_list doesn't have push_back function. I've tried a few approaches.

1
2
3
4
5
6
7
    std::forward_list<int> number;
    std::forward_list<int>::iterator i;
    
    
    i = number.insert_after(number.before_begin(), 2);
    color.insert_after(i, 3);
    color.push_front(1);


But this exceeds 4 lines.

1
2
3
4
5
    std::forward_list<int> number;
    
    number.insert_after(numbers.before_begin(), 2);
    number.insert_after(numbers.begin(), 3);
    number.push_front(1);


I also have this. The order is correct but I'm not sure they follow the commands above closely.

What do you think?
I'm not familiar with using forward_list, but if you like the first approach you listed, and your only problem with it is the fact that the relevant code takes five lines, then you can easily amend it to take use only four lines, thus:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
#include <forward_list>

int main()
{
 std::forward_list<int> numbers;
 std::forward_list<int>::iterator i = numbers.insert_after(numbers.before_begin(), 2);
 numbers.insert_after(i, 3);
 numbers.push_front(1);

 // just to check the list contents
 for (auto it = numbers.begin(); it != numbers.end(); ++it ) std::cout << ' ' << *it;
}

Output:
 1 2 3 

But then I see the second piece of code seems to work anyway, without using the iterator.

1
2
3
4
 std::forward_list<int> numbers;
 numbers.insert_after(numbers.before_begin(), 2);
 numbers.insert_after(numbers.begin(), 3);
 numbers.push_front(1);

Output:
 1 2 3 

This may be useful if you've not already seen it:
http://www.cplusplus.com/reference/forward_list/forward_list/

Not sure that helps any at all, but I know there will be other people more clued up on this stuff to help you.
Last edited on
Topic archived. No new replies allowed.