| An envelope around the stdlib div function that returns a struct of quotient and remainder. | Lecture 2 - slide 18 : 42 Program 3 |
// C++ In A Nutshell example, page 36. Three version of divide.
// div returns an object that aggregates the quotient and the remainder.
#include <iostream>
#include <cstdlib>
// The type ldiv_t is a struct with a quotient and a remainder field.
void divide_1 (long num, long den, long& quo, long& rem){
std::ldiv_t result = std::div(num, den); // The struct is COPIED out of div
quo = result.quot;
rem = result.rem;
}
void divide_2 (long num, long den, long& quo, long& rem){
const std::ldiv_t& result = std::div(num, den); // The struct is NOT COPIED out of div.
quo = result.quot; // Instead a const reference is established
rem = result.rem; // to the resulting struct.
// This most likely involves creating a temporary struct, however.
}
void divide_3 (long num, long den, long& quo, long& rem){
std::ldiv_t& result = std::div(num, den); // error: invalid initialization of non-const reference of type ldiv_t&
quo = result.quot;
rem = result.rem;
}
int main(){
using namespace std;
long q, r;
divide_1(107, 20, q, r);
cout << q << " remainder " << r << endl; // 5 remainder 7
divide_2(107, 20, q, r);
cout << q << " remainder " << r << endl; // 5 remainder 7
}