linked list with templates

Hi,
Is it possible to create linked list class with templates?
if it is, can you bring me a small example?

thanks.

It's funny you ask, I'm currently working on mine. Here is a link to the original thread: http://www.cplusplus.com/forum/beginner/76498/

If you want more information, you can check a more detailed version of the list here: http://www.cplusplus.com/forum/general/85346/
thanks !
but why did you write "struct" instead of "class"?
and the templated list must include same data members?
for example class T and some integer i, and another list with double.
possible ?
but why did you write "struct" instead of "class"?

My understanding of struct, and still is, is that they're basically the same. The only main difference is that members of a struct are public and the members of a class are private by default. This doesn't mean anything if you get in the habit of declaring access for you members.

and the templated list must include same data members?

I believe you meant you must include all of the same data types. If so, yes. If you make a list of integers, you can only add integers to it (minus some typecasting). But that's the purpose of a list. If you make a grocery list to go to the store, you're not going to put all of your family and friends' birthday on it.

for example class T and some integer i, and another list with double. possible ?

Yes, you can make as many different lists as you want. That's the beauty of templates. You can even make up your own class to use.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <list>

class Names {
   // Some Stuff
}

// Some Other Stuff

int main() {
   std::list<int> myIntList;
   std::list<double> myDoubleList;
   std::list<Names> myNamesList;

   return 0;
}


I hope that answered your questions. If you're unsure, you can always play around with the standard library list. You can't do any damage, but it may help your understanding a bit better. Just remember, a linked list allows you to read through the list from the top to the end only (unless it's doubly linked, then you can read it end to top), you can't just get an item out of the middle of it like you can with a vector. There are a bunch of different containers if you want to see what you can and can't do with each of them.
Thanks a lot !!!
where can i see the standard library list?
closed account (E0p9LyTq)
Mor1994 wrote:
where can i see the standard library list?

http://www.cplusplus.com/reference/list/list/
http://en.cppreference.com/w/cpp/container/list
closed account (E0p9LyTq)
std::list is a double-linked list. If you are looking for single-linked list, use std::forward_list.
http://www.cplusplus.com/reference/forward_list/forward_list/
http://en.cppreference.com/w/cpp/container/forward_list

You can't directly access a list's or forward_list's elements by position, as you can do with an array or a std::vector.
Topic archived. No new replies allowed.