C++. Please leave comments explaining. Thank you! Given two unsorted STL lists X
ID: 3792200 • Letter: C
Question
C++. Please leave comments explaining. Thank you!
Given two unsorted STL lists X and P , write a valid C++ function intersection( X , P ) that returns a new list that contains the elements common to both X and P .
For example, if X = 5, 2, 1, 4 and P = 4, 5, 7; your algorithm should return a new list containing 5 and 4 (order is not important).
Also specify the running time of your algorithm using Big-Oh notation. Hint: As the lists are unsorted, a straightforward algorithm would need a double for loop.
Explanation / Answer
#include<bits/stdc++.h>
using namespace std;
list<int> intersection(list<int>& x,list<int>& p)
{
list<int> r;
for (std::list<int>::iterator it = x.begin(); it != x.end(); it++)
{
for (std::list<int>::iterator it1= p.begin(); it1 != p.end(); it1++)
{
if(*it==*it1)
r.push_back(*it);
}
}
return r;
}
int main(int argc, char const *argv[])
{
list<int> x;
x.push_back(1);
x.push_back(3);
x.push_back(2);
list<int> p;
p.push_back(1);
p.push_back(3);
list<int> r=intersection(x,p);
for (std::list<int>::iterator it = r.begin(); it != r.end(); it++)
{
cout<<*it<<" ";
}
return 0;
}
===================================================================
akshay@akshay-Inspiron-3537:~$ g++ interse.cpp
akshay@akshay-Inspiron-3537:~$ ./a.out
1 3
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.