List<> in C++

closed account (G1vDizwU)
Hi guys,

Consider we have a list as follows:

list<char> lch = { 'H', 'e', 'l', 'l', 'o' };

How to move over it (for example) to write out the elements using a loop, please?

Thanks.
Last edited on
See the example code in the reference for begin()
http://www.cplusplus.com/reference/list/list/begin/
The iterator using begin and end will work for other standard containers as well as std::string.

There is also the c++11 range-based for loop which is simpler to use.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <list>
#include <string>
#include <vector>


template <class T>
void display(const T & values)
{
    for (auto it=values.begin(); it!=values.end(); ++it)
        std::cout << *it << ' ';
    std::cout << '\n';
}

template <class T>
void show(const T & values)
{
    for (auto a : values)
        std::cout << a << ' ';
    std::cout << '\n';
}


int main()
{
    std::vector <char> vec = { 'H', 'e', 'l', 'l', 'o' };
    std::list   <char> lis = { 'H', 'e', 'l', 'l', 'o' };
    std::string str= "Hello";
    
    display(vec);
    display(lis);
    display(str);    
    
    show(vec);
    show(lis);
    show(str);
}


not sure whether this will post - had a technical difficulty replying to this thread.
closed account (G1vDizwU)
Thank you both very much.
Topic archived. No new replies allowed.