0

I know how to have a linked list in c++ and use add method to input entries by entries. However, I do not want to add entries by entries. Is there a way to declare a linkedlist with initial values in the list?

For example, if I want to have {1, 2 , 3 , 4, 5} and as many elements as i want in the list is there something I can do in one line? Something like:

LinkedList<int> list = new LinkedList<int>(1,2,3,4,5);

AdnanArch
  • 54
  • 7
  • This is what you are looking for: https://en.cppreference.com/w/cpp/utility/initializer_list – Asesh Nov 04 '22 at 04:15
  • You are probably looking for `std::initializer_list`. See e.g. constructor (10) [here](https://en.cppreference.com/w/cpp/container/list/list) – Igor Tandetnik Nov 04 '22 at 04:16
  • It looks like you are asking if the initialization of `words1` in [this example](https://en.cppreference.com/w/cpp/container/list/list#Example) is possible. Tough one, but since there is an example of it, I would go with "yes". Would you like to rephrase your question so that the answer is longer than one word? (That is, go ahead and assume it is possible, no need to ask "is there something I can do".) – JaMiT Nov 04 '22 at 04:28
  • The thing is i do not want to include any built in library in my code as i am building my own linked list from scratch so can you help me with that? @JaMiT – AdnanArch Nov 04 '22 at 04:32
  • @Asesh this includes vector and initializer_list but i want to build linked list by my own. – AdnanArch Nov 04 '22 at 04:34
  • @AdnanArch I did not say use `std::lsit` in your code. I said use `std::list` to conclude that your goal is possible. Instead of *"and as many elements as i want in the list is there something I can do in one line?"*, try "and as many elements as i want in the list, *similar to what `std::list` manages to do. **How** do I write a constructor for this?"* – JaMiT Nov 04 '22 at 04:41
  • Yeah it is not possible to write a constructor for this i know. – AdnanArch Nov 04 '22 at 04:47

1 Answers1

0

std::list helps you achieve this using an intializer list

#include <iostream>
#include <list>

using namespace std;

int main()
{
    list<int> l {1,2,3,4,5}; // This is the line you are looking for
    
    for(auto &e : l) {
        cout << e << " "; // Print contents of l
    }

    return 0;
}

Output: 1 2 3 4 5

Suraj
  • 1
  • 1