Reputation: 13
I have a function that accepts two vectors v1 and v2. Compares the elements in both of them and is supposed to return the common elements from both. Both vectors have 5 strings in them.
It doesn't work as expected, though. For example, I enter for v1:
dog cat lizard snake pig
and v2 has:
cat sheep cow snake fish
The result though is:
snake
How can I fix it so that the output would look something like the follow?
cat snake
my code
#include <iostream>
#include <vector>
#include <string>
using namespace std;
const int CAPACITY = 5;
template <typename t>
vector <t> inter(const vector <t> & v1, const vector <t> & v2)
{
vector <t> v3;
for(int i = 0; v1.size(); i++ )
{
for(int j= 0; v2.size(); j++)
{
if (v1[i] == v2[j])
{
v3.push_back(v1[i]);
}
}
}
return v3;
}
int main()
{
vector<string> vec1;
string a;
cout << "Enter five stings for vector 1 \n"<< endl;
for(int i = 0; i< CAPACITY; i++ )
{
cin >> a;
vec1.push_back(a);
}
vector<string> vec2;
string b;
cout << "Enter five stings for vector 2 \n"<< endl;
for(int i = 0; i< CAPACITY; i++ )
{
cin >> b;
vec2.push_back(b);
}
cout<<inter(vec1, vec2);
}
Upvotes: 0
Views: 1003
Reputation: 178
For the inter function, first change the return type to a vector, then use the v3 vector you are currently not using for the below operations.
vector<t> inter(const vector <t> & v1, const vector <t> & v2)
{
vector<t> v3;
for(int i=0; i<v1.size(); i++)
{
for(int j=0; j<v2.size(); j++)
{
if(v1[i] == v2[j])
{
v3.push_back(v1[i])
}
}
}
return v3;
}
To print out the contents you have to assign the returned vector to a variable and then loop through it as such...
vector<t> vec3 = inter(vec1, vec2);
for(int i=0; i<vec3.size(); i++)
{
cout<<vec3.at(i)<<" ";
}
That will return a vector containing all of the answers, make sure to make the changes to the loop as before your loop was only checking if they were in the same place, not if they were both in the vector
Be mindful that this will produce duplicate results in the case of {x, x, y} and {x, z , a}
Upvotes: 0
Reputation: 45410
Use std::set_intersection algorithm is much easier, it requires two sorted vectors:
template <typename T>
std::vector<T> inter(const std::vector<T> & v1, const std::vector<T> & v2)
{
std::vector<T> v3;
std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3));
return v3;
}
std::sort(vec1.begin(), vec1.end()); // sort vec1
std::sort(vec2.begin(), vec2.end()); // sort vec2
std::vector<std::string> v3 = inter(vec1, vec2);
See sample code
Upvotes: 2
Reputation: 283624
Well, your inter
function has a few problems:
Upvotes: 1
Reputation: 272487
One option is to sort both vectors, and then use std::set_intersection
.
Upvotes: 5