I need help with the following problem, I keep getting errors on the code. Can s
ID: 3779270 • Letter: I
Question
I need help with the following problem, I keep getting errors on the code. Can some please look at my code and help fix the errors. It is in C++
The code is below
Write a function void downsize(list& names) that removes every second value from a linked list.
#include<iostream>
#include<string>
#include<list>
#include<cstdlib>
#include<stack>
using namespace std;
int main()
{
list names;
string input;
list::iterator iter;
int downsize(list&);
for(int i=0;i<5 ;i++)
{
cin>>input;
names.push_back(input);
}
downsize(names);
cout<<" update list is: ";
for (iter=names.begin();iter!=names.end();iter++)
{
cout<<*iter<
}
return 0;
}
int downsize(list& names)
{
list::iterator pos;
for(pos = names.begin(); pos!=names.end();)
{
pos++;
if(pos!=names.end())
pos = names.erase(pos);
}
}
Explanation / Answer
// C++ code
#include <iostream>
#include <string>
#include <list>
#include <cstdlib>
#include <stack>
using namespace std;
// function to remove every second value from a linked list
void downsize(list<string>& names)
{
list<string>::iterator pos;
for(pos = names.begin(); pos!=names.end();)
{
pos++;
if(pos!=names.end())
pos = names.erase(pos);
}
}
int main()
{
// correct format of list
list<string> names;
string input;
list<string>::iterator iter;
// input list
cout << "Enter list: ";
for(int i=0;i<5 ;i++)
{
cin>>input;
names.push_back(input);
}
// call function
downsize(names);
// print updated list
cout<<" update list is: ";
for (iter=names.begin();iter!=names.end();iter++)
{
cout<<*iter<< endl;
}
return 0;
}
/*
output:
Enter list:
alex
hales
riaz
jason
roy
update list is:
alex
riaz
roy
*/