14 - Vector Example

From Maryville College CS Wiki
Jump to: navigation, search

roman.cpp

// Vector based implementation of Roman Numerals
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
    //value of roman numerals from largest to smallest
    vector<int> value = { 1000, 900, 500, 400,
                          100, 90, 50, 40,
                          10, 9, 5, 4,
                          1 };

    //roman digits in the same order of the values
    vector<string> digit = { "M", "CM", "D", "CD",
                             "C", "XC", "L", "XL",
                             "X", "IX", "V", "IV",
                             "I" };

    int num;                //number in Indian Numerals
    string roman_number;    //the roman number

    //read in a number
    cout << "Enter a number: ";
    cin >> num;


    //loop over the values 
    for(int i=0; i < value.size(); i++) {
        //find how many of this value we need to create
        int n = num / value[i];

        //take this portion out of the number
        num = num % value[i];

        //put that many of this symbol into the string
        while(n > 0) {
            roman_number += digit[i];  //concatenate the digit
            n--;
        }
    }
    
    //display the roman numeral
    cout << roman_number << endl;
}