Template help!
May 31, 2013 at 7:27am UTC
I have two template functions, which one of them checks whether two vector containers have the same elements with the same multiplicities, and another template function that removes the duplicated elements. However, the output only displays the last element that I have pushed to the vector container. What am I doing wrong?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template <class T>
bool same_elements(const vector<T> &val1, const vector<T> &val2)
{
if (val1.size() != val2.size())
return false ;
};
template <class T>
void remove_duplicates(vector<T> &val)
{
sort(val.begin(), val.end());
val.erase(unique(val.begin(), val.end()), val.end());
};
int main(int argc, const char * argv[])
{
int v1Size, d1Elem, v2Size, d2Elem;
vector<int > v1, v2;
cout << "Input number of elements for integer v1: " ;
cin >> v1Size;
for (int i=0; i<v1Size; i++)
{
cout << "Input data: " ;
cin >> d1Elem;
}
for (int i=0; i<v1Size; i++)
v1.push_back(d1Elem);
cout << "Input number of elements for integer v2: " ;
cin >> v2Size;
for (int i=0; i<v2Size; i++)
{
cout << "Input data: " ;
cin >> d2Elem;
}
for (int i=0; i<v2Size; i++)
v2.push_back(d2Elem);
if (same_elements(v1, v2))
cout << "v1 and v2 contain same elements." << endl;
else
cout << "v1 and v2 contents are different." << endl;
cout << "After remove duplicates from v1, now it contains:" << endl;
remove_duplicates(v1);
for (int i=0; i<v1Size; i++)
cout << d1Elem << ' ' ;
cout << endl;
cout << "After remove duplicates from v2, now it contains:" << endl;
remove_duplicates(v2);
for (int i=0; i<v2Size; i++)
cout << d2Elem << ' ' ;
cout << endl;
return 0;
}
May 31, 2013 at 7:35am UTC
1 2 3 4 5 6 7
for (int i=0; i<v1Size; i++)
{
cout << "Input data: " ;
cin >> d1Elem;
} // diElem has the last value you entered
for (int i=0; i<v1Size; i++)
v1.push_back(d1Elem); //all the elements are equal to the last value entered.
similarly for the other vector
Last edited on May 31, 2013 at 7:35am UTC
May 31, 2013 at 7:45am UTC
abhishekm71,
So should I change the d1Elem so that it holds the elements entered, not just the last value I entered?
this is not good?
May 31, 2013 at 7:48am UTC
You just comibine the loops. no need for two loops.
1 2 3 4 5 6
for (int i=0; i<v1Size; i++)
{
cout << "Input data: " ;
cin >> d1Elem;
v1.push_back(d1Elem);
}
Last edited on May 31, 2013 at 7:48am UTC
May 31, 2013 at 7:52am UTC
Still gets same output.. ><
May 31, 2013 at 7:56am UTC
while outputting also you are using d1Elem. you have to use v1[i] and v2[i] respectively.
Also, you may want to re-check your same_elements function. It just checks whether the number of elements in both vectors are equal.
Topic archived. No new replies allowed.