Sort a string of Roman numerals
The input will be a string of Roman numerals, which must be sorted by their meaning. Also this task needs to be completed using classes in C ++
So far I have created my class
#include<iostream>
#include<string>
using namespace std;
class RomanNumbers
{
public:
RomanNumbers(string = "");
void setRoman(string);
int convertToDecimal();
void printDecimal();
void printRoman();
private:
string roman;
int decimal;
};
And functions for converting a number from roman numeral to integer form, but my question is how do I sort them, because I cannot create a new string that will contain the converted roman numerals and sort the string. Any help would be appreciated.
#include<iostream>
#include<string>
#include "RomanNumbers.h"
using namespace std;
RomanNumbers::RomanNumbers(string myRoman)
{
roman = myRoman;
decimal = 0;
}
void RomanNumbers::setRoman(string myRoman)
{
roman = myRoman;
decimal = 0;
}
int RomanNumbers::convertToDecimal()
{
enum romans { I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000 };
for (int i = 0; i < roman.size(); i++)
{
switch (roman[i])
{
case 'M': decimal += M; break;
case 'D': decimal += D; break;
case 'C': decimal += C; break;
case 'L': decimal += L; break;
case 'X': decimal += X; break;
case 'V': decimal += V; break;
case 'I':
if (roman[i + 1] != 'I' && i + 1 != roman.size())
{
decimal -= 1;
}
else
{
decimal += 1;
}
break;
}
}
return decimal;
}
void RomanNumbers::printRoman()
{
cout << "Number in Roman form : " << roman;
cout << endl;
}
void RomanNumbers::printDecimal()
{
cout << "Number converted in integer form : " << decimal;
cout << endl;
}
source to share
One way to solve your problem is to define a meaningful comparison operator<
/ comparison lambda expression / compare class, which will then be used along with the algorithm sort
:
template <class RandomAccessIterator, class Compare>
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
for example comparison class:
struct RomanComp
{
bool operator() const (const RomanNumbers& lhs, const RomanNumbers& rhs)
{
return lhs.decimal < rhs.decimal;
}
} RomanComparator; // <--- note object instantiation
and then, for example, to sort the roman number vector:
std::vector<RomanNumbers> nums;
std::sort(nums.begin(), nums.end(), RomanComparator);
given that:
#include <algorithm> // std::sort
#include <vector> // std::vector
source to share