how to compare strings in vector in c++? - c++

hey I have class containing
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <iomanip>
using namespace std;
struct student
{
std::string ID;
std::string Name;
std::vector<std::string> friends;
};
And main function contains
int main() {
vector<student> List_Students = { { "d123", "Jacob", {"e321"} }, { "e321", "Abo", {"d123", "e456"} }, { "e456","Mark",{} } };
for (auto& s : List_Students)
{
cout << s.ID << "\t" << s.Name;
for (auto& f : s.friends)
{
cout << " " << f << " ";
}
cout << endl;
}
}
this yields output as expected
output:
d123 Jacob e321
e321 Abo d123 e456
e456 Mark
my question is how can I compare the vector of friends with IDs so that so that after it shows friends it shows their names with it. Expected output:
d123 Jacob e321 (Abo)
e321 Abo d123 (Jacob) e456 (Mark)
e456 Mark (No friends)
quite new to c++ any help would be appreciated thank you

You can use the standard std::find_if() algorithm, eg
...
#include <algorithm>
...
int main() {
vector<student> List_Students = {
{ "d123", "Jacob", {"e321"} },
{ "e321", "Abo", {"d123", "e456"} },
{ "e456", "Mark", {} }
};
for (auto& s : List_Students)
{
cout << s.ID << "\t" << s.Name;
if (s.friends.empty())
{
cout << " (No friends)";
}
else
{
for (auto& f : s.friends)
{
cout << " " << f << " ";
auto iter = find_if(List_Students.begin(), List_Students.end(),
[&](const student &s2){ return s2.ID == f; }
);
if (iter != List_Students.end())
{
cout << "(" << iter->Name << ") ";
}
}
}
cout << endl;
}
}
Or, like #Ch3steR said in comments, you can store the names in a std::map:
...
#include <map>
#include <utility>
...
int main() {
vector<student> List_Students = {
{ "d123", "Jacob", {"e321"} },
{ "e321", "Abo", {"d123", "e456"} },
{ "e456", "Mark", {} }
};
map<string, string> names;
for (auto& s : List_Students)
{
names.insert(make_pair(s.ID, s.Name));
}
for (auto& s : List_Students)
{
cout << s.ID << "\t" << s.Name;
if (s.friends.empty())
{
cout << " (No friends)";
}
else
{
for (auto& f : s.friends)
{
cout << " " << f << " (" << names[f] << ") ";
}
}
cout << endl;
}
}
Alternatively:
#include <iostream>
#include <string>
#include <map>
using namespace std;
struct student
{
string Name;
vector<string> friends;
};
int main() {
map<string, student> List_Students = {
{ "d123", { "Jacob", {"e321"} } },
{ "e321", { "Abo", {"d123", "e456"} } },
{ "e456", { "Mark", {} } }
};
for (auto& elem : List_Students)
{
auto &s = elem.second;
cout << elem.first << "\t" << s.Name;
if (s.friends.empty())
{
cout << " (No friends)";
}
else
{
for (auto& f : s.friends)
{
cout << " " << f << " (" << List_Students[f].Name << ") ";
}
}
cout << endl;
}
}

Related

A class that contains a member of the same class

I would Like to construct a class that contains itself but I have to avoid an endless loop. For example I started of my class
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class box {
protected:
int id;
vector<box*> intmega;
int n = 10;
public:
box(box const& autre, int id) : n(autre.n), id(id) {
for (auto& element : autre.get_intmega()) {
intmega.push_back(new box(*element, id + 100));
}
cout << "A new object has seen light" << endl;
}
box(int id) : n(10), id(id) { cout << "Created Box" << endl; }
void ajoute2(box& autre) { intmega.push_back(new box(autre)); }
int size_() const { return intmega.size(); }
int number() const { return n; }
box* get() { return intmega[0]; }
vector<box*> get_intmega() const { return intmega; }
int getId() const { return id; }
~box() {
cout << this << endl;
for (auto element : this->intmega)
delete element;
}
};
void affichel(box const& autre) {
cout << "Box :" << autre.getId() << endl;
cout << "Box :" << &autre << endl;
}
void affiche(box& autre) {
for (auto* element : autre.get_intmega()) {
affichel(*element);
affiche(*element);
cout << endl;
}
}
int main() {
box box1(1);
box box2(2);
box box3(3);
box2.ajoute2(box3);
box1.ajoute2(box2);
box box4(box1, 4);
affiche(box1);
cout << "Box1 Address : " << &box1 << endl;
affiche(box4);
cout << "Box4 Address : " << &box4 << endl;
return 0;
}
Everything works fine but upon calling the destructor disaster.
It deletes all objects but it gets into an endless loop of deleting an object that has already been deleted. Any suggestions help?
I made those slight modifications and now my program works just fine.
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class box
{
protected:
vector<box*> intmega;
int n = 10;
public:
box(box const &autre) : n(autre.n)
{
for (auto &element : autre.get_intmega())
{
intmega.push_back(new box(*element));
}
cout << "A new object has seen light" << endl;
cout<<this<<endl;
}
box()
{
cout << "Created Box" << endl;
cout<<this<<endl;
}
void ajoute2(box & autre){
intmega.push_back(new box(autre));
}
int size_() const
{
return intmega.size();
}
int number() const
{
return n;
}
vector<box *> get_intmega() const
{
return intmega;
}
~box()
{
cout<<this<<endl;
for(auto element: this->intmega){
delete element;
}
}
};
void affichel(box const &autre)
{
cout << "Box :" << &autre<< endl;
}
void affiche(box &autre)
{
for (auto *element : autre.get_intmega())
{
affichel(*element);
affiche(*element);
cout << endl;
}
}
int main()
{
box box1;
box box2;
box box3;
box box4;
box3.ajoute2(box4);
box2.ajoute2(box3);
box1.ajoute2(box2);
box box5(box1);
affiche(box1);
cout << "Box1 Address : " << &box1 << endl ;
affiche(box5);
cout << "Box5 Address : " << &box4 << endl ;
return 0;
}

Error while Pushing Elements from a std::string onto a Stack of String Type

I get this error while trying to loop through a string to push each element onto a stack of string type s1 in my isPalindrome() function.
no instance of overloaded function "std::stack<_Ty, _Container>::push
[with _Ty=std::string, _Container=std::deque>]" matches the argument list
When I assign, the element that is at the top of the stack to a string variable an error pops up:
'std::stack>>::top':
non-standard syntax; use '&' to create a pointer to member
Why does it mention std::deque?
#include <iostream>
#include <string>
#include <stack>
#include <algorithm>
class Palindrome
{
public:
Palindrome();
void inputString();
std::string convert2lower();
bool isPalindrome();
private:
std::string userstring;
std::stack<std::string> s1;
};
Palindrome::Palindrome()
{}
void Palindrome::inputString()
{
std::cout << "Enter a string: ";
std::getline(std::cin,userstring);
}
std::string Palindrome::convert2lower()
{
userstring.erase(remove(userstring.begin(), userstring.end(), ' '), userstring.end());
userstring.erase(std::remove_if(userstring.begin(), userstring.end(), ispunct), userstring.end());
transform(userstring.begin(), userstring.end(), userstring.begin(), tolower);
return userstring;
}
bool Palindrome::isPalindrome()
{
size_t n = userstring.size();
for (size_t i = 0; i < n; ++i)
{
s1.push(userstring[i]);
}
std::string reversed;
for (size_t i = 0; i < n; ++i)
{
std::string temp = s1.top;
reversed.insert(i,temp);
s1.pop();
}
if (reversed == userstring)
{
return true;
}
return false;
}
int main()
{
Palindrome p1;
p1.inputString();
std::cout << "\nCalling convert2lower(): " << std::endl;
std::cout << "The new string is " << p1.convert2lower() << std::endl;
std::cout << "\nCalling isPalindrome(): " << std::endl;
if (!p1.isPalindrome())
{
std::cout << "String is NOT a Palindrome!" << std::endl;
}
else
{
std::cout << "String is a Palindrome!" << std::endl;
}
}
Here is your code fixed with the absolute minimum changes...
#include <iostream>
#include <string>
#include <stack>
#include <algorithm>
class Palindrome
{
public:
Palindrome();
void inputString();
std::string convert2lower();
bool isPalindrome();
private:
std::string userstring;
std::stack<char> s1;
};
Palindrome::Palindrome()
{}
void Palindrome::inputString()
{
std::cout << "Enter a string: ";
std::getline(std::cin, userstring);
}
std::string Palindrome::convert2lower()
{
userstring.erase(remove(userstring.begin(), userstring.end(), ' '), userstring.end());
userstring.erase(std::remove_if(userstring.begin(), userstring.end(), ispunct), userstring.end());
transform(userstring.begin(), userstring.end(), userstring.begin(), tolower);
return userstring;
}
bool Palindrome::isPalindrome()
{
size_t n = userstring.size();
for (size_t i = 0; i < n; ++i)
{
s1.push(userstring[i]);
}
std::string reversed;
for (size_t i = 0; i < n; ++i)
{
char temp = s1.top();
reversed.insert(i, &temp, 1);
s1.pop();
}
if (reversed == userstring)
{
return true;
}
return false;
}
int main()
{
Palindrome p1;
p1.inputString();
std::cout << "\nCalling convert2lower(): " << std::endl;
std::cout << "The new string is " << p1.convert2lower() << std::endl;
std::cout << "\nCalling isPalindrome(): " << std::endl;
if (!p1.isPalindrome())
{
std::cout << "String is NOT a Palindrome!" << std::endl;
}
else
{
std::cout << "String is a Palindrome!" << std::endl;
}
}
Here are answers to your questions:
no instance of...this is caused by using string instead of char as the stack type.
non standard syntax...this is because you left the () off of pop.
deque is mentioned because stack is a specialization of deque.

c++ netplan ubuntu yaml read and create

i have create a c++ app and need to read Ubuntu Netplan yaml files.
I found many websites with a lot of helpful information. mostly everything just does not work with netplan files. it crashes every time, usually when I set the root node to network. However, it is necessary because you still do not know what network card it is.
network.yaml
network:
ethernets:
eth0:
addresses:
- 192.168.0.30/24
dhcp4: false
gateway4: "192.168.0.1"
nameservers:
addresses:
- "211.211.190.30"
- "211.160.60.1"
- "8.8.8.8"
search:
- Network.local
renderer: networkd
version: 2
it must save into a struct for another works.
Parsing yaml with yaml cpp
yaml-cpp Easiest way to iterate through a map with undefined values
yaml-cpp read sequence in item
http://albertocorona.com/yaml-cpp-a-small-tutorial-to-serialization/
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <dirent.h>
#include <yaml-cpp/yaml.h>
#include <yaml-cpp/node/node.h>
#include <yaml-cpp/node/iterator.h>
using namespace std;
static string path02 = "/Netzwerk.yaml";
struct NetInfo {
int ID;
string version;
string renderer;
string IF_Type;
string name;
string dhcp4;
vector<string> addresseIF;
string gateway4;
vector<string> NSsearch;
vector<string> NSaddress;
};
int main(){
NetInfo yamlsafe;
YAML::Node config = YAML::LoadFile(path02);
string NetzwerkTyp = config["network"]["ethernets"].as<std::string>();
string NetzManager = config["network"]["renderer"].as<string>();
string If_Name = config["network"]["eth0"].as<string>();
string DHCP4 = config["eth0"]["addresses"].as<string>();
string IP = config["eth0"]["dhcp4"].as<string>();
string Gateway = config["eth0"]["gateway4"].as<string>();
string NS_IP = config["nameservers"]["addresses"].as<string>();
string NS_Search = config["nameservers"]["search"].as<string>();
cout <<"NetzwerkTyp:" << "\t" << NetzwerkTyp << endl;
cout <<"Netz Manager:" << "\t" << NetzManager << endl;
cout <<"If-Name:" << "\t" << If_Name << endl;
cout <<"DHCP4" << "\t" << DHCP4 << endl;
cout <<"IP" << "\t" << IP << endl;
cout <<"Gateway" << "\t" << Gateway << endl;
cout <<"NS-IP" << "\t" << NS_IP << endl;
cout <<"NS-Search" << "\t" << NS_Search << endl;
//second test
YAML::Node config1 = YAML::LoadFile(path02);
const YAML::Node& sensors = config1["network"];
for (YAML::const_iterator it = sensors.begin(); it != sensors.end(); ++it) {
const YAML::Node& sensor = *it;
std::cout << "address: " << sensor["addresses"].as<std::string>() << "\n";
std::cout << "dhcp: " << sensor["dhcp4"].as<std::string>() << "\n";
}
return 0;
}
yes i had the same think i've bin see this tipe but
nothing is what it makes. it hange up the QT ide.
my second thing is the second test below.
YAML::Node config1 = YAML::LoadFile(path02);
const YAML::Node& node1 = config1["network"];
//network: ------------------------>node2
const YAML::Node& node2 = node1["network"]["ethernets"];
// ethernets: ------------------>node3
const YAML::Node& node3 = node2["ethernets"]["eth0"];
// eth0: --------------------->node4
const YAML::Node& node4 = node3["eth0"]["addresses"];
// addresses: ----------------------N1-> - seq1
const vector& node4s1 = node4["addresses"];
// - 192.168.0.30/24-----------------> - seq1 -p1
const YAML::Node& node4 = node3["eth0"]["dhcp4"];
// dhcp4: false ------------------>node4-2
const YAML::Node& node4 = node3["eth0"]["gateway4"];
// gateway4: "192.168.0.1"-------->node4-3
const YAML::Node& node4 = node3["eth0"]["nameservers"];
// nameservers: ------------------>node4-4
const vector& node4s2 = node4["nameservers"]["addresses"];
// addresses: --------------------N5-> - seq2
// - "211.211.190.30"--------------> - seq2 - p1
// - "211.160.60.1"----------------> - seq2 - p2
// - "8.8.8.8"---------------------> - seq2 - p3
const vector& node4s3 = node4["nameservers"]["search"];
// search: -----------------------N6-> - seq3
// - Network.local-----------------> - seq3 - p1
const YAML::Node& node2 = node1["network"]["renderer"];
// renderer: networkd---------->node5
const YAML::Node& node2 = node1["network"]["version"];
// version: 2------------------>node6
this is what i thing about it but it is not working.
Ok this is the answer i have a struct and i can read all nodes.
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <dirent.h>
#include <yaml-cpp/yaml.h>
#include <yaml-cpp/node/iterator.h>
using namespace std;
struct DateiLesen {
string version;
string renderer;
string IF_Type;
string name;
string dhcp4;
string dhcp6;
vector<string> addresseIF;
string gateway4;
string gateway6;
vector<string> NSsearch;
vector<string> NSaddress;
};
static vector<DateiLesen> DLS2;
static string path = "/QTProjects/YAML-15/test/Netzwerk.yaml";
void Yaml_lesen(){
YAML::Node nodew = YAML::LoadFile(path);
string NetIf = "eth0";
DLS2.push_back(DateiLesen());
if (nodew["network"]) {
if (nodew["network"]["version"]) {
DLS2[0].version = nodew["network"]["version"].as<string>();
//std::cout << nodew["network"]["version"].as<std::string>() << "\n";
}
if (nodew["network"]["renderer"]) {
DLS2[0].renderer = nodew["network"]["renderer"].as<std::string>();
//std::cout << nodew["network"]["renderer"].as<std::string>() << "\n";
}
if (nodew["network"]["ethernets"]) {
DLS2[0].IF_Type = "ethernets";
if (nodew["network"]["ethernets"][NetIf]) {
if (nodew["network"]["ethernets"][NetIf]["dhcp4"]) {
DLS2[0].dhcp4 = nodew["network"]["ethernets"][NetIf]["dhcp4"].as<string>();
//std::cout << nodew["network"]["ethernets"][NetIf]["dhcp4"].as<std::string>() << "\n";
}
if (nodew["network"]["ethernets"][NetIf]["dhcp6"]) {
DLS2[0].dhcp6 = nodew["network"]["ethernets"][NetIf]["dhcp6"].as<string>();
//std::cout << nodew["network"]["ethernets"][NetIf]["dhcp6"].as<std::string>() << "\n";
}
if (nodew["network"]["ethernets"][NetIf]["addresses"]) {
if (nodew["network"]["ethernets"][NetIf]["addresses"].IsSequence()) {
for (unsigned long it = 0; it < nodew["network"]["ethernets"][NetIf]["addresses"].size(); ++it) {
DLS2[0].addresseIF.push_back(nodew["network"]["ethernets"][NetIf]["addresses"][it].as<std::string>());
//cout << nodew["network"]["ethernets"][NetIf]["addresses"][it].as<std::string>() << "\n";
}
}
}
if (nodew["network"]["ethernets"][NetIf]["gateway4"]) {
DLS2[0].gateway4 = nodew["network"]["ethernets"][NetIf]["gateway4"].as<string>();
//std::cout << nodew["network"]["ethernets"][NetIf]["gateway4"].as<std::string>() << "\n";
}
if (nodew["network"]["ethernets"][NetIf]["gateway6"]) {
DLS2[0].gateway6 = nodew["network"]["ethernets"][NetIf]["gateway6"].as<string>();
//std::cout << nodew["network"]["ethernets"][NetIf]["gateway4"].as<std::string>() << "\n";
}
if (nodew["network"]["ethernets"][NetIf]["nameservers"]) {
//cout << "Nameservers" << endl;
if (nodew["network"]["ethernets"][NetIf]["nameservers"]["search"]) {
if (nodew["network"]["ethernets"][NetIf]["nameservers"]["search"].IsSequence()) {
for (unsigned long it = 0; it < nodew["network"]["ethernets"][NetIf]["nameservers"]["search"].size(); ++it) {
DLS2[0].NSsearch.push_back(nodew["network"]["ethernets"][NetIf]["nameservers"]["search"][it].as<std::string>());
//cout << nodew["network"]["ethernets"][NetIf]["nameservers"]["search"][it].as<std::string>() << "\n";
}
}
}
if (nodew["network"]["ethernets"][NetIf]["nameservers"]["addresses"]) {
if (nodew["network"]["ethernets"][NetIf]["nameservers"]["addresses"].IsSequence()) {
for (unsigned long it = 0; it < nodew["network"]["ethernets"][NetIf]["nameservers"]["addresses"].size(); ++it) {
DLS2[0].NSaddress.push_back(nodew["network"]["ethernets"][NetIf]["nameservers"]["addresses"][it].as<std::string>());
//cout << nodew["network"]["ethernets"][NetIf]["nameservers"]["addresses"][it].as<std::string>() << "\n";
}
}
}
}
}
}else if(nodew["network"]["wifis"]){
DLS2[0].IF_Type = "wifis";
if (nodew["network"]["wifis"][NetIf]) {
if (nodew["network"]["wifis"][NetIf]["dhcp4"]) {
DLS2[0].dhcp4 = nodew["network"]["wifis"][NetIf]["dhcp4"].as<string>();
//std::cout << nodew["network"]["wifis"][NetIf]["dhcp4"].as<std::string>() << "\n";
}
if (nodew["network"]["wifis"][NetIf]["dhcp6"]) {
DLS2[0].dhcp6 = nodew["network"]["wifis"][NetIf]["dhcp6"].as<string>();
//std::cout << nodew["network"]["wifis"][NetIf]["dhcp6"].as<std::string>() << "\n";
}
if (nodew["network"]["wifis"][NetIf]["addresses"]) {
if (nodew["network"]["wifis"][NetIf]["addresses"].IsSequence()) {
for (unsigned long it = 0; it < nodew["network"]["wifis"][NetIf]["addresses"].size(); ++it) {
DLS2[0].addresseIF.push_back(nodew["network"]["wifis"][NetIf]["addresses"][it].as<std::string>());
//cout << nodew["network"]["wifis"][NetIf]["addresses"][it].as<std::string>() << "\n";
}
}
}
if (nodew["network"]["wifis"][NetIf]["gateway4"]) {
DLS2[0].gateway4 = nodew["network"]["wifis"][NetIf]["gateway4"].as<string>();
//std::cout << nodew["network"]["wifis"][NetIf]["gateway4"].as<std::string>() << "\n";
}
if (nodew["network"]["wifis"][NetIf]["gateway6"]) {
DLS2[0].gateway6 = nodew["network"]["wifis"][NetIf]["gateway6"].as<string>();
//std::cout << nodew["network"]["wifis"][NetIf]["gateway4"].as<std::string>() << "\n";
}
if (nodew["network"]["wifis"][NetIf]["nameservers"]) {
cout << "Nameservers" << endl;
if (nodew["network"]["wifis"][NetIf]["nameservers"]["search"]) {
if (nodew["network"]["wifis"][NetIf]["nameservers"]["search"].IsSequence()) {
for (unsigned long it = 0; it < nodew["network"]["wifis"][NetIf]["nameservers"]["search"].size(); ++it) {
DLS2[0].NSsearch.push_back(nodew["network"]["wifis"][NetIf]["nameservers"]["search"][it].as<std::string>());
//cout << nodew["network"]["wifis"][NetIf]["nameservers"]["search"][it].as<std::string>() << "\n";
}
}
}
if (nodew["network"]["wifis"][NetIf]["nameservers"]["addresses"]) {
if (nodew["network"]["wifis"][NetIf]["nameservers"]["addresses"].IsSequence()) {
for (unsigned long it = 0; it < nodew["network"]["wifis"][NetIf]["nameservers"]["addresses"].size(); ++it) {
DLS2[0].NSaddress.push_back(nodew["network"]["wifis"][NetIf]["nameservers"]["addresses"][it].as<std::string>());
//cout << nodew["network"]["wifis"][NetIf]["nameservers"]["addresses"][it].as<std::string>() << "\n";
}
}
}
}
}
}else if(nodew["network"]["bonds"]){
}else if(nodew["network"]["bridges"]){
}else if(nodew["network"]["vlans"]){
}
}
}
int main(){
Yaml_lesen();
for (unsigned long S = 0; S < DLS2.size(); S++){
cout << DLS2[S].renderer << endl;
cout << DLS2[S].name << endl;
cout << DLS2[S].IF_Type << endl;
cout << DLS2[S].dhcp4 << endl;
for (unsigned long S2 = 0; S2 < DLS2[S].addresseIF.size(); S2++){
cout << DLS2[S].addresseIF[S2] << endl;
}
cout << DLS2[S].gateway4 << endl;
for (unsigned long S2 = 0; S2 < DLS2[S].addresseIF.size(); S2++){
cout << DLS2[S].NSsearch[S2] << endl;
}
for (unsigned long S2 = 0; S2 < DLS2[S].addresseIF.size(); S2++){
cout << DLS2[S].NSaddress[S2] << endl;
}
}
return 0;
}

C++ print out objects error

I am getting stuck on print the object Meja1 and Meja2 into class Informasi.
How I can print the object Meja1.print_Meja(); and Meja2.print_Meja();
and please advice me how I can write my code into human readable coding style?
#include <iostream>
#include <string.h>
using namespace std;
class Inventaris {
private:
string Jenis;
string Warna;
string Keadaan;
public:
void setInventaris (string a, string u, string g)
{
Jenis=a;
Warna=u;
Keadaan=g;
}
string getJenis()
{
return Jenis;
}
string getWarna()
{
return Warna;
}
string getKeadaan()
{
return Keadaan;
}
void cetak ()
{
cout<<"Info Inventaris adalah :"<<endl;
cout<<"Jenis : "<<getJenis()<<endl;
cout<<"Warna : "<<getWarna()<<endl;
cout<<"Keadaan : "<<getKeadaan()<<endl;
}
};
class Kursi : public Inventaris {
public:
void print_Kursi(){
hitung++;
cout << "Informasi kursi adalah" <<endl;
cout<<"Jenis : "<<getJenis()<<endl;
cout<<"Warna : "<<getWarna()<<endl;
cout<<"Keadaan : "<<getKeadaan()<<endl;
}
static int hitung;
static getHitung()
{
return hitung;
}
};
class Meja : public Inventaris {
public:
void print_Meja(){
cout << "Informasi Meja adalah" <<endl;
cout<<"Jenis : "<<getJenis()<<endl;
cout<<"Warna : "<<getWarna()<<endl;
cout<<"Keadaan : "<<getKeadaan()<<endl;
hitung_meja++;
}
static int hitung_meja;
static getHitung_meja()
{
return hitung_meja;
}
};
class Informasi : public Meja, public Kursi {
public:
void print_info(){
cout << "Informasi" <<endl;
cout << "Jumlah Meja = " << Meja::getHitung_meja() << endl;
Meja1.print_Meja(); // how I print object Meja1 and Meja2
Meja2.print_Meja();
cout << "Jumlah Kursi = " << Kursi::getHitung() << endl;
}
};
int Kursi::hitung = 0;
int Meja::hitung_meja = 0;
int main() {
Kursi Kursi1;
Kursi1.setInventaris("Kursi goyang","Merah muda", "Bekas");
Kursi1.print_Kursi();
cout << endl;
Kursi Kursi2;
Kursi2.setInventaris("Kursi kakek","reyot", "Bekas");
Kursi2.print_Kursi();
cout << endl;
Meja Meja1;
Meja1.setInventaris("Meja Antik","Coklat tua","Bekas");
Meja1.print_Meja();
cout << endl;
Meja Meja2;
Meja2.setInventaris("Meja Coffee","Hijau Robek","Bekas");
Meja2.print_Meja();
cout << endl;
Informasi info;
info.print_info();
}
I fixed your code and I made Meja1 and Meja2 global declarations so they are accessible by main() and Informasi class.
#include <iostream>
#include <string>
using namespace std;
class Inventaris {
private:
string Jenis;
string Warna;
string Keadaan;
public:
void setInventaris(string a, string u, string g)
{
Jenis = a;
Warna = u;
Keadaan = g;
}
string getJenis()
{
return Jenis;
}
string getWarna()
{
return Warna;
}
string getKeadaan()
{
return Keadaan;
}
void cetak()
{
cout << "Info Inventaris adalah :" << endl;
cout << "Jenis : " << getJenis() << endl;
cout << "Warna : " << getWarna() << endl;
cout << "Keadaan : " << getKeadaan() << endl;
}
};
class Kursi : public Inventaris {
public:
void print_Kursi() {
hitung++;
cout << "Informasi kursi adalah" << endl;
cout << "Jenis : " << getJenis() << endl;
cout << "Warna : " << getWarna() << endl;
cout << "Keadaan : " << getKeadaan() << endl;
}
static int hitung;
static int getHitung() // <--- FIXED!
{
return hitung;
}
};
class Meja : public Inventaris {
public:
void print_Meja() {
cout << "Informasi Meja adalah" << endl;
cout << "Jenis : " << getJenis() << endl;
cout << "Warna : " << getWarna() << endl;
cout << "Keadaan : " << getKeadaan() << endl;
hitung_meja++;
}
static int hitung_meja;
static int getHitung_meja() // <--- FIXED!
{
return hitung_meja;
}
};
Meja Meja1; // <--- Global declaration accessible by main() and Informasi
Meja Meja2; // <--- Global declaration accessible by main() and Informasi
class Informasi : public Meja, public Kursi {
public:
void print_info() {
cout << "Informasi" << endl;
cout << "Jumlah Meja = " << Meja::getHitung_meja() << endl;
Meja1.print_Meja();
Meja2.print_Meja();
cout << "Jumlah Kursi = " << Kursi::getHitung() << endl;
}
};
int Kursi::hitung = 0;
int Meja::hitung_meja = 0;
int main() {
Kursi Kursi1;
Kursi1.setInventaris("Kursi goyang", "Merah muda", "Bekas");
Kursi1.print_Kursi();
cout << endl;
Kursi Kursi2;
Kursi2.setInventaris("Kursi kakek", "reyot", "Bekas");
Kursi2.print_Kursi();
cout << endl;
Meja1.setInventaris("Meja Antik", "Coklat tua", "Bekas");
Meja1.print_Meja();
cout << endl;
Meja2.setInventaris("Meja Coffee", "Hijau Robek", "Bekas");
Meja2.print_Meja();
cout << endl;
Informasi info;
info.print_info();
}

map of member functions of heterogenous types

I am trying to write a map of heterogeneous function pointers and have mimicked that in a smaller program which has functions to either take a "int" or a "double" val.
#include <iostream>
#include <boost/any.hpp>
#include <map>
#include <sstream>
using namespace std;
class Functions
{
public:
void intF(int f) { cout << " Value int : " << f << endl; }
void doubleF(double f) { cout << " Value double : " << f << endl; }
};
const boost::any convertInt(const string& s)
{
cout << " string passed : " << s << endl;
std::istringstream x(s);
int i;
x >> i;
cout << " Int val : " << i << endl;
return i;
}
const boost::any convertDouble(const string& s)
{
cout << " string passed : " << s << endl;
std::istringstream x(s);
double i;
x >> i;
cout << " Double val : " << i << endl;
return i;
}
typedef void (Functions::*callFunc)( const boost::any);
typedef const boost::any (*convertFunc)( const string&);
struct FuncSpec
{
convertFunc _conv;
callFunc _call;
};
FuncSpec funcSpec[] = {
{ &convertInt, (callFunc)&Functions::intF },
{ &convertDouble, (callFunc)&Functions::doubleF },
};
int main()
{
string s1("1");
string s2("1.12");
callFunc c = funcSpec[0]._call;
convertFunc co = funcSpec[0]._conv;
Functions F;
(F.*c)(((*co)(s1)));
c = funcSpec[1]._call;
co = funcSpec[1]._conv;
(F.*c)(((*co)(s2)));
return 0;
}
When I run this program, I see the double value getting printed correctly but the int value is garbled. Could someone help me with this? Also is there a better way to achieve this functionality. In my program I have 2 functions - one taking a vector<int> and the other taking a vector<double>. I have to read the data from a file and call the appropriate setters in the object of the class which has these 2 functions.
Casting a member function to a different type like you are doing isn't valid. Try this instead:
class Functions
{
public:
void intF(boost::any input)
{
int f = boost::any_cast<int>(input);
cout << " Value int : " << f << endl;
}
void doubleF(boost::any input)
{
double f = boost::any_cast<double>(input);
cout << " Value double : " << f << endl;
}
};
.
.
.
FuncSpec funcSpec[] = {
{ &convertInt, &Functions::intF },
{ &convertDouble, &Functions::doubleF },
};