Home > Back-end >  Why is my code not working properly? Is there something in STL-list which I am forgetting?
Why is my code not working properly? Is there something in STL-list which I am forgetting?

Time:01-30

This is my code:

#include <iostream>

#include <list>

using namespace std;

template <class T>

void display(list<T> l){

    list<int>::iterator i;
    for (i = l.begin(); i != l.end(); i  )
    {
        cout << *i << " ";
    }
}

void enter(list<int> l){

    list<int>::iterator i;
    int index = 1;
    for (i = l.begin(); i != l.end(); i  , index  )
    {
        // cout << "check" << endl;
        cout << "Enter element at index " << index << endl;
        cin >> *i;

    }
    
    
}

int main(){

    list<int> l;
    display(l);
    cout << endl;
    l.push_front(1);
    l.push_front(2);
    l.push_front(3);
    l.push_front(4);
    l.push_front(5);

    list<int> l2(3);
    enter(l2);
    display(l2);
    cout << "EXE";
    return 0;
}

The output of the following program is:

Enter element at index 1

1

Enter element at index 2

2

Enter element at index 3

3

0 0 0 EXE

Required Output:

Enter element at index 1

1

Enter element at index 2

2

Enter element at index 3

3

1 2 3 EXE

CodePudding user response:

The issue is that you pass the list by value in enter. When you update the list with cin >> *i, you are updating a copy of l2 instead of the l2 declared in main().

If you would like to update the list you will need to pass by reference instead.

void enter(list<int>& l){

  list<int>::iterator i;
  int index = 1;
  for (i = l.begin(); i != l.end(); i  , index  )
  {
      // cout << "check" << endl;
      cout << "Enter element at index " << index << endl;
      cin >> *i;

  }
}
  •  Tags:  
  • Related