In: Computer Science
Rewrite the Jars problem to use a Jar class and a vector of Jar objects
The Jar class has 2 private members - volume, capacity, a default constructor, a 1 parameter constructor, 2 accessors but only 1 mutator, two boolean methods isEmpty and IsFull, a 1 Jar reference parameter method, pour, that pours the contents of its parameter into the method's Jar
jar.h
#include <algorithm>
#include <vector>
using namespace std;
class Jar
{
public:
Jar(int new_capacity =8);
bool isEmpty();
bool isFull();
int getvolume();
int getcapacity();
int pour(Jar&);
private:
int capacity;
int volume;
};
jar.cpp
#include "jar.h"
Jar::Jar(int new_capacity)
{
if(new_capacity <=0)
new_capacity =8;
capacity = new_capacity;
volume =0;
}
bool Jar::isEmpty()
{
return true;
}
bool Jar::isFull()
{
return true;
}
int Jar::getvolume()
{
return 0;
}
int Jar::getcapacity()
{
return 0;
}
int Jar::pour(Jar& jar)
{
int this_avail = capacity - volume;
//int jar_avail = jar.valume;
int pour_amt =0;
volume += pour_amt;
jar.volume -= pour_amt;
return pour_amt;
}
main.cpp
#include <iostream>
#include <vector>
#include "jar.h"
using namespace std;
int main()
{
int jar;
vector<Jar>Jar ={(8), (5), (3)};
Jar[0].pour(Jar[1]);
do
{
cout<<"read source " <<endl;
cout<<"read distination " <<endl;
int srce =0;
int dest = 1;
Jar[dest].pour(Jar[srce]);
cout<< Jar[0].getvolume()<< " "<<
Jar[0].getvolume()<<Jar[0].getvolume()<<endl;
}while(Jar[1].getvolume()!=4);
return 0;
}
Ans: Solution
1) Empty Function
#include <iostream>
#include <stack>
using
namespace
std;
int
main()
{
stack<
int
>
mystack;
mystack.push(1);
// Stack becomes
1
if
(mystack.empty()) {
cout
<<
"True"
;
}
else
{
cout
<<
"False"
;
}
return
0;
}
2) Final Value Function
#include <iostream>
#include <stack>
using
namespace
std;
int
main()
{
int
sum
= 0;
stack<
int
>
mystack;
mystack.push(1);
mystack.push(8);
mystack.push(3);
mystack.push(6);
mystack.push(2);
// Stack becomes 1,
8, 3, 6, 2
while
(!mystack.empty()) {
sum
= sum + mystack.top();
mystack.pop();
}
cout <<
sum;
return
0;
}
3) Stack Size
#include <iostream>
#include <stack>
using
namespace
std;
int
main()
{
int
sum
= 0;
stack<
int
>
mystack;
mystack.push(1);
mystack.push(8);
mystack.push(3);
mystack.push(6);
mystack.push(2);
// Stack becomes 1,
8, 3, 6, 2
cout <<
mystack.size();
return
0;
}
4) Check till Stack Size = 0
#include <iostream>
#include <stack>
using
namespace
std;
int
main()
{
int
sum
= 0;
stack<
int
>
mystack;
mystack.push(1);
mystack.push(8);
mystack.push(3);
mystack.push(6);
mystack.push(2);
// Stack becomes 1,
8, 3, 6, 2
while
(mystack.size() > 0) {
sum
= sum + mystack.top();
mystack.pop();
}
cout <<
sum;
return
0;
}