Frequency Function

I need to write a frequency function in order that numbers don't repeat when output vector 3 and common elements unless it shows up in V1 and V2 twice. Such as V1: 1 9 3 -1 3 2 V2: 3 2 10 -8 -10 -5 3 So in common vectors it would be the following: 3 3 2

How would I write and implement a frequency function in my following code please.


#include<iostream>
#include<vector>
#include<cstdlib>
#include<time.h>

using namespace std;

void output(vector <int> V1, vector<int> V2) //outputs V1 and V2
{
cout << "Vector V1 contents: ";
for(int i=0; i<V1.size(); i++)
{
cout << V1[i] << " ";
}
cout << endl<< endl;

cout << "Vector V2 contents: ";
for(int i=0; i<V2.size(); i++)
{
cout << V2[i] << " ";
}
cout << endl<< endl;
}

void fill_vector(vector<int>& V1, vector<int>& V2) //fills vectors with random numbers
{
srand((int)(time(0)));
for (int i=0; i< V1.size();++i)
{
V1[i]=rand()% 21 +(-10);

}

for (int i=0; i< V2.size(); ++i)
{
V2[i]=rand()%21+ (-10);

}

}


vector<int> common_elements(vector<int> &V1, vector<int> &V2) //lists common elements of V1 and V2
{


vector<int> common;


for (int i=0; i< V1.size(); i++)
{
for (int j=0; j< V2.size(); j++)
{
if( V1[i] == V2[j])
{
cout<< V1[i] << " ";
}
}
}

cout<< endl<< endl;
return common;
}

vector<int> not_in_the_other_vector(vector<int> &V1, vector<int> &V2)
{
vector<int> different;


for (int i=0; i< V1.size(); i++)
{

if(V1[i] != V2[i])

cout<< V1[i] << " ";

}

cout<< endl<< endl;

cout<< "Elements that are in V2, but are not in V1: ";
for (int i=0; i<V2.size(); i++)
{
if( V2[i]!= V1[i])
cout<< V2[i] << " ";
}
cout<< endl<< endl << endl;
return different;
}

vector<int> unique(vector<int>& V1, vector<int>& V2){
vector<int> a1 = not_in_the_other_vector(V1, V2);
vector<int> a2 = not_in_the_other_vector(V2, V1);
vector<int> unique_elements;

cout << "Unique elements:\n";

for (int i=0; i<a1.size(); i++){
unique_elements.push_back(a1[i]);
cout << a1[i] << " ";
}
for (int i=0; i<a2.size(); i++){
unique_elements.push_back(a2[i]);
cout << a2[i] << " ";
}
cout << endl;

return unique_elements;
}



int main()
{
int size1;
int size2;
cout<< "How big do you want V1 to be? ";
cin>> size1;
cout<< "How big do you want V2 to be? ";
cin>> size2;
vector<int> V1(size1);
vector<int> V2(size2);

fill_vector(V1, V2);
output( V1, V2);

cout<< "Elements that are common to both vectors: ";
common_elements (V1,V2);

cout<< "Elements that are in V1, but not in V2: ";
not_in_the_other_vector(V1, V2);

cout << "Unique elements of V1 and V2: ";
unique(V1, V2);


cout<< endl;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//lists common elements of V1 and V2
vector<int> common_elements(vector<int> &V1, vector<int> &V2) 
{
  vector<int> common;
  
  for (size_t i = 0; i < V1.size(); ++i)
  {
    if (find(V2.begin(), V2.end(), V1.at(i)) != V2.end())
    {
      common.push_back(V1.at(i));
    }
  }
  return common;
}
Topic archived. No new replies allowed.