You are given a list, L, and another list, P, containing integers sorted in ascending order. The operation printLots(L, P) will print the elements in L that are in positions specified by P. For instance, if P = 1, 3, 4, 6, the elements in positions 1, 3, 4, and 6 in L are printed. Write the procedure printLots(L, P). You may use only the public STL container operations. What is the running time of your procedure?
The solution is provided in the code snippet provided below using vector of STL.
Vector are same as dynamic arrays placed in contiguous storage .
// printLots prints elements in vector L at positions specified in vector P
void printLots(vector<int> L, vector<int> P)
{
// This for loop runs for every element in P
// P.size() returns the number of elements in vector P
for (int i = 0; i < P.size(); i++)
{
// This line will print elememts in L where i is the current position accessed in P
// and (P[i] - 1) is the required position in L
// since the vector starts from 0th location.
cout << L[ P[i] - 1 ]<<" ";
}
}
The running time of this procedure is equal to the number of elements/values in vector P which will be equal to P.size() as for loop runs P.size() times.
Get Answers For Free
Most questions answered within 1 hours.