Skip to content

Instantly share code, notes, and snippets.

@NicolaBernini
Last active August 26, 2019 13:11
Show Gist options
  • Save NicolaBernini/5173c0b28937d98adfed877229730234 to your computer and use it in GitHub Desktop.
Save NicolaBernini/5173c0b28937d98adfed877229730234 to your computer and use it in GitHub Desktop.
Minimal element-wise comparison function in CPP for linear containers

Overview

Minimal element-wise comparison function in CPP working with

  • a container type providing

    • element counting semantic, via size()

    • direct element access semantic, via []

  • a contained type providing

    • order operator, via < and >
#include <iostream>
#include <vector>
#include <array>
using namespace std;
// Performing element-wise comparison on a containers pair with the same number of elements and returning a vector where for the i-th position
// the -1 means the i-th element in the first is bigger than the i-th in second
// the +1 means the i-th element in the second is bigger than the i-th in the first
// the 0 means the i-th elements in first and second can not be ordered hence it is assumed they are equal (but no explicit use of the equal semantic is done)
template <typename T>
vector<int> compare(const T& a, const T& b)
{
if(a.size() != b.size()) throw std::runtime_error("Different size");
vector<int> c(a.size());
for(auto i=0; i<a.size(); ++i)
{
if(a[i] < b[i]) c[i]=1;
else if(a[i] > b[i]) c[i]=-1;
else c[i]=0;
}
return c;
}
int main() {
// your code goes here
vector<int> a1 = {1,5,8,11,31};
vector<int> b1 = {2,4,9,12,32};
auto c1 = compare(a1,b1);
for(const auto& e : c1) cout << e << endl;
array<int, 5> a2 = {1,6,5,8,22};
array<int, 5> b2 = {2,6,4,9,25};
auto c2 = compare(a2,b2);
for(const auto& e : c2) cout << e << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment