0

I was trying to implement a n-tuple from scratch starting with the mathematical base ordered-pair where n-tuple (a,b,c) = ordered_pair(a,ordered_pair(b,c)) and ordered pair is a set representation ie. ordered_pair(a,b) = set{{a},{a,b}}

here is the code for ordered_pair

#include <iostream>
#include <set>
#include <boost/variant.hpp>
using namespace std;
template <typename T, typename U, typename Z>
class orderd_pair{

//typedef boost::variant<int,std::string,double> cell;
private:
set<set<Z>> opair;

set<T> first;
set<U> second;

public:

set<set<Z>> Orderd_pair(T first_element, U second_element){

first.insert(first_element);
second.insert(first_element);
second.insert(second_element);
opair.insert(first);
opair.insert(second);

return opair;

}
//TO DO void print_elements(std::set<std::set<cell>> opair);*/

};

the problem is when trying to implement tuple set of each ordered_pair must be nested ie for three element tuple set{{a},{a,{{b},{b,c}}}} and for more elements it will be nested even more making it hard to work with, how can I solve this??

also I have used boost::variant to support int,std::string and double data types.

  • 1
    Why are you doing this? If it’s so hard to work with, why don’t you use `std::tuple`? – mkrieger1 Feb 14 '20 at 08:12
  • Do you limit your implementation on purpose to `int, std::string, double` or do you just not know how to make it generic? Also are they really supposed to be interchangable (i.e. is it allowed to replace a string with an int, cause that is what variant is doing) – Timo Feb 14 '20 at 08:18

1 Answers1

0

You will quickly find that you can't put a std::set<T> into the same container as a std::set<U> if T is different to U. So you are likely to end up with

struct any_less {
    bool operator()(const std::any & lhs, const std::any & rhs) { 
        return type_index(lhs.type()) < type_index(rhs.type()); 
    }
}

using ordered_pair = std::set<std::set<std::any, any_less>>;

Codifying your recurrence relation.

template <typename A, typename B>
ordered_pair make_ordered_pair(A a, B b) {
    return { { a }, { a, b } };
}

template <typename A, typename B, typename C, typename... Rest>
ordered_pair make_ordered_pair(A a, B b, C c, Rest... rest) {
    return { { a }, { a, make_ordered_pair(b, c, rest...) } };
}

But C++ has a much better type for ordered pairs: std::pair. It also has a much better type for tuples: std::tuple.

Caleth
  • 52,200
  • 2
  • 44
  • 75