Home > Back-end >  How to get frequency of std:vectors in C ?
How to get frequency of std:vectors in C ?

Time:11-01

I have 5 vectors. I want to check how many times these vectors exist. I used the following code to compare if 2 vectors are equal, but now I have more than 2 vectors. I want to compare all these 5 vectors together and count how many times each vector exists. How can I do it? Any help would be appreciated.

The output should be:

(0,0,1,2,3,0,0,0) = 2 time(s)

(0,0,1,2,3,4,0,0) = 1 time(s)

(0,0,2,4,3,0,0,0) = 1 time(s)

(0,0,6,2,3,5,6,0) = 1 time(s)

#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;

void checkVec(vector<int> v){
   vector<int> v0;
   if(v0 == v){
      cout << "Equal\n";
   }
   else{
      cout << "Not Equal\n";
   }
}

int main(){
    vector<int> v1={0,0,1,2,3,0,0,0};
    vector<int> v2={0,0,1,2,3,4,0,0};
    vector<int> v3={0,0,2,4,3,0,0,0};
    vector<int> v4={0,0,1,2,3,0,0,0};
    vector<int> v5={0,0,6,2,3,5,6,0};

    checkVec(v1);
    return 0;
}

CodePudding user response:

You can use std::map counting the number of occurences of each vector:

#include <map>
#include <vector>
#include <iostream>
using vec = std::vector<int>;

int main(){
    vec v1={0,0,1,2,3,0,0,0};
    vec v2={0,0,1,2,3,4,0,0};
    vec v3={0,0,2,4,3,0,0,0};
    vec v4={0,0,1,2,3,0,0,0};
    vec v5={0,0,6,2,3,5,6,0};


    std::map<vec,std::size_t> counter;
    // Initializer list creates copies by default
    // But you should not create vX variables anyway.
    for(const auto& v: {v1,v2,v3,v4,v5}){
          counter[v];
    }

    std::cout<<"V1 is present " <<counter[v1]<<" times.\n";

    return 0;
}
V1 is present 2 times.

CodePudding user response:

Well, this is a contribution for Quimby answer, but if you know how many vectors you will get at compile time, use std::array to contain all that vector. If you know it at runtime instead, use std::vector as shown below

#include <map>
#include <vector>
#include <iostream>
#include <cstddef>

int main(){

    std::vector<std::vector<int>> allVector
    {
         std::vector<int>{0,0,1,2,3,0,0,0},
         std::vector<int>{0,0,1,2,3,4,0,0},
         std::vector<int>{0,0,2,4,3,0,0,0},
         std::vector<int>{0,0,1,2,3,0,0,0},
         std::vector<int>{0,0,6,2,3,5,6,0},
    };


    std::map<std::vector<int>, std::size_t> counter;

    for(const auto& v : allVector)
    {
            counter[v];
    }
    // print out the array and it's frequency
    for(const auto& pr : counter)
    {
            std::cout << '(';
            for(std::size_t i {0}; i < pr.first.size();   i)
            {
                std::cout << pr.first[i];
                if(i != pr.first.size() - 1)
                    std::cout << ' ';
            }
            std::cout << ") = " << pr.second << ", ";

    }

    return 0;
}
  • Related