In: Computer Science
C++ mainDisplay.cpp
Write the function displayAt that receives the two STL lists; vList and pList. The function should display the elements in vList that are in positions specified by pList. For example, if pList has the elements (2, 5, 6, 8) then the elements in positions 2, 5, 6, and 8 in vList are displayed. Use only the public STL container operations.
Solution:
I have written the function in C++ 11
Note:
Since It is mentioned as positions so the numbering starts from 1 not from 0. .
If you require any changes in the function please comment and I will do the needful.
Code of the function:
void displayAt(list <int> vList,list <int> pList)
{
list <int> :: iterator it=pList.begin();
for (int val : vList)
{
it=next(pList.begin(), val-1);
cout<<"Element at position "<<val<<": "<<*it<<endl;
}
}
Complete implementation with code:
#include <iostream>
#include <list>
using namespace std;
void displayAt(list <int> vList,list <int> pList)
{
list <int> :: iterator it=pList.begin();
for (int val : vList)
{
it=next(pList.begin(), val-1);
cout<<"Element at position "<<val<<": "<<*it<<endl;
}
}
int main()
{
list <int> vList({2,5,6,8});
list <int> pList({1,2,3,4,5,6,7,8,9,10});
displayAt(vList,pList);
return 0;
}
Screenshot of output: