I have a class for performing various array operations. I like to use my insert method in my populate method.
Can someone guide me on that? Here is the code:
#include <iostream>
#include <cstdlib>
using namespace std;
const int MAX=5;
class array
{
private:
int arr[MAX];
public:
void insert(int pos, int num);
void populate(int[]);
void del(int pos);
void reverse();
void display();
void search(int num);
};
void array::populate(int a[])
{
for (int i=0;i<MAX;i++)
{
arr[i]=a[i];
}
}
void array::insert(int pos, int num)
{
for (int i=MAX-1;i>=pos;i--)
{
arr[i] = arr[i-1];
arr[i]=num;
}
}
void array::del(int pos)
{
for (int i=pos;i<MAX;i++)
{
arr[pos]=arr[pos + 1];
}
}
void array::display()
{
for (int i=0;i<MAX;i++)
cout<<arr[i];
}
void array::search(int num)
{
for (int i=0;i<MAX;i++)
{
if (arr[i]==num)
{
cout<<"\n"<<num<<" found at index "<<i;
break;
}
if (i==MAX)
{
cout<<num <<" does not exist!";
}
}
}
int main()
{
array a;
for (int j=0;j<MAX;j++)
{
a.insert(j,j);
}
a.populate(a);
a.insert(2,7);
a.display();
a.search(44);
system("pause");
}
I like to use my insert method in my
populate method. Can someone guide me
on that?
That would mean that instead of the straightforward and efficient "copy from one array to another" approach, you'd call insert for each value of the input with the correct index in place of the assignment.
To call a method on the current instance, from inside a method:
insert(x, y);
//or
this->insert(x, y);
Your code also contains an error, in that you pass a wrong type to populate in main. It expect int* (a real array), not an array object.
Please elaborate your question. If you just need a good container have a look at the STL (Standard Template Library) std::vector. It's part of the C++ standard and comes with your compiler.
If you want to learn how to write a custom class, please try to be more precise in your question.
Also consider the wealth of beginner tutorials available on the net, for example:
http://www.learncpp.com/
Here is a little example on how to write a custom class with one member function calling the other and accessing a private data member (note that inside a member function you can refer to any other member directly):
#include <iostream>
class Example
{
private:
int some_private_stuff;
public:
Example();
void function_a();
void function_b();
};
Example::Example(){
some_private_stuff = 1;
}
void Example::function_a(){
std::cout << "this is function a" << std::endl;
some_private_stuff = 2;
std::cout << "changed private_stuff to " << some_private_stuff << std::endl;
}
void Example::function_b(){
std::cout << "this is function b" << std::endl;
function_a();
}
int main() {
Example e;
e.function_b();
return 0;
}
Related
This has been driving me insane for hours - I'm new to C++: I can't figure out why my programs thinks I want it do this.
I have a class House
class House{
private:
int number;
std::string family;
public:
House(int n, std::string f){
this->number = n;
this->family = f;
}
House(){
this->number = 0;
this->family = "unassigned";
}
void whoLivesHere(){
std::cout<<"The"<<family<<"lives here."<<std::endl;
}
};
I have another class Neighborhood
class Neighborhood{
private:
int size;
House houses[100];
public:
Neighborhood(){
this->size=0;
}
void addHouse(House h){
this->houses[this->size] = h;
this->size++;
}
void whoLivesHere(){
for(int i=0; i<this->size; i++){
this->houses[this->size].whoLivesHere();
}
}
};
And this is what is happening on my main.
int main(){
Neighborhood n1;
House h1(1,"Johnsons");
House h2(1,"Jones");
n1.addHouse(h1);
n1.addHouse(h2);
n1.whoLivesHere();
return 0;
}
And what I get on the Terminal is this.
The unassigned lives here
The unassigned lives here
The unassigned lives here
Why didn't the new objects replace the first two default objects?
Why show three objects? If size should be 1.
Thank you tonnes in advance!
You can make short work of this problem by using the tools the C++ Standard Library gives you, like this:
#include <string>
#include <vector>
#include <iostream>
int main() {
std::vector<House> neighborhood;
// emplace_back() forwards arguments to the constructor
neighborhood.emplace_back(1, "Johnson");
neighborhood.emplace_back(2, "Jones");
// No need to track size, std::vector does that for you: size(),
// but that's not even needed to iterate, you can just do this:
for (auto& house : neighborhood) {
house.whoLivesHere();
}
return 0;
}
Here I've cleaned up your House implementation:
class House {
private:
int number;
std::string family;
public:
// Tip: Use constructor lists
House(int n, const std::string& f) : number(n), family(f) { };
// Useful even for defaults
House() : number(0), family("unassigned") { };
// Flag methods that don't modify anything as const
void whoLivesHere() const {
std::cout << "The " << family << " lives here at number " << number << "." << std::endl;
}
};
I've been working on this assignment for my class for about a day and I've completed just about everything. The only thing I'm missing is removing my array and replacing it with a vector.
#ifndef MENU
#define MENU
#include <vector>
const int MAXCOUNT = 20;
struct menuItem
{
void(*func)();
char decript[50];
};
class Menu
{
private:
//vector <int> v; i tried replacing the "mi"'s in the menu.cpp file with v.push_back but i kept getting pointer errors
menuItem mi[MAXCOUNT];
int count = 0;
void runSelection();
public:
Menu();
void addMenu(char *Description, void(*f)());
void runMenu();
void waitKey();
};
#endif
This is the cpp file. Im trying to replace the array mi with v. I know im missing something but I can't figure it out so I'm just posting it working with an array.
Menu::Menu()
:count(0)
{
}
void Menu::addMenu(char *Description, void(*f)())
{
if (count < MAXCOUNT)
{
this->mi[count].func = f;
strcpy(this->mi[count].decript, Description);
count++;
}
}
void Menu::runMenu()
{
for (;;)
{
system("CLS");
for (int i = 0; i < count; i++)
{
cout << this->mi[i].decript << endl;
}
runSelection();
}
}
void Menu::waitKey()
{
cout << "Press any key to continue" << endl;
while (!_kbhit());
fflush(stdin);
}
void Menu::runSelection()
{
int select;
cin >> select;
if (select <= count)
this->mi[select - 1].func();
}
The simplest way should be to replace
menuItem mi[MAXCOUNT];
with
std::vector<menuItem> mi;
and initialize it in your constructor properly
Menu::Menu()
:count(0)
,mi(MAXCOUNT)
{
}
Supposed you had working code before, this should replace the raw array seamlessly.
With the current c++ standard you can even simply use
std::array<menuItem,MAXCOUNT> mi;
this wouldn't even require initialization in the constructor.
I created the following class
#include "cliques.h"
#include "vector"
#include <iostream>
using namespace std;
cliques::cliques(){
}
cliques::cliques(int i) {
clique.push_back(i);
clique_prob = 1;
mclique_prob = 1;
}
cliques::cliques(const cliques& orig) {
}
cliques::~cliques() {
}
void cliques::addvertex(int i) {
clique.push_back(i);
}
double cliques::getclique_prob() const {
return clique_prob;
}
double cliques::getMaxclique_prob() const {
return mclique_prob;
}
void cliques::showVertices() {
for (vector<int>::const_iterator i = clique.begin(); i !=clique.end(); ++i)
cout << *i << ' ';
cout << endl;
}
vector<int> cliques::returnVector() {
return clique;
}
void cliques::setclique_prob(double i) {
clique_prob = i;
}
void cliques::setMaxclique_prob(double i) {
mclique_prob = i;
}
Here's the header file
#include "vector"
#ifndef CLIQUES_H
#define CLIQUES_H
class cliques {
public:
void addvertex(int i);
cliques();
cliques(int i);
cliques(const cliques& orig);
virtual ~cliques();
double getclique_prob() const;
double getMaxclique_prob() const;
void showVertices();
std::vector<int> returnVector();
void setclique_prob(double i);
void setMaxclique_prob(double i);
private:
float clique_prob;
float mclique_prob;
std::vector <int> clique;
};
#endif /* CLIQUES_H */
I want to create a vector of these objects in order to implement a heap
int main(int argc, char** argv) {
cliques temp(1);
cliques temp1(2);
temp.setclique_prob(0.32);
temp.setclique_prob(0.852);
temp.showVertices();
temp1.showVertices();
vector <cliques> max_heap;
max_heap.push_back(temp);
max_heap.push_back(temp1);
double x =max_heap.front().getclique_prob();
cout<<"prob "<<x<<endl;
cliques y = max_heap.front();
y.showVertices();
//make_heap (max_heap.begin(),max_heap.end(),max_iterator());
//sort_heap (max_heap.begin(),max_heap.end(),max_iterator());
return 0;
}
For reasons unknown to me none of my class functions work properly after i create my vector, meaning that while the following function works as intended
temp.showVertices()
the next one doesn't,
y.showVertices()
You miss implementation for
cliques::cliques(const cliques& orig) {
}
STL vector uses copy constructor inside when you add values to it. As your cliques class does not allocate any memory, you can just remove the copy constructor from the code and compiler will generate one for you.
I am having trouble in initializing an array of structures with a function pointer as a member in it.
class Record
{
private:
typedef void (*display_fn_t) ();
struct record {
int a;
display_fn_t disp;
};
static const record rec[];
void disp1() { cout << "Display 1 with a string to display" << endl; }
void disp2() { cout << "Display 2 with an integer to display" << endl; }
public:
int find() { /* logic to find the record comes here */ }
void display() {
for (int i = 0; i < 2; i++) {
rec[i].disp();
}
}
}
const Record::record Record::rec[] = {
{ 10, disp1 },
{ 11, disp2 }
};
int main()
{
Record r;
if (r.find())
r.display();
return 0;
}
When I compile the above code, I am getting the following compilation error:
mca_record.cpp:56: error: argument of type ‘void (Record::)()’ does
not match ‘void (*)()’
Your syntax is wrong and isn't using the appropriate operators.
Fixing a multitude of syntax errors, and stripping out the unrelated find operation, then utilizing proper member function pointers and operator ->* gives the following (one of several ways to do this):
#include <iostream>
class Record
{
private:
typedef void (Record::*display_memfn_t)();
struct record
{
int a;
display_memfn_t disp;
};
static const record rec[];
void disp1() { std::cout << "Display 1 with a string to display" << std::endl; }
void disp2() { std::cout << "Display 2 with an integer to display" << std::endl; }
public:
void display();
};
const Record::record Record::rec[] =
{
{ 10, &Record::disp1 },
{ 11, &Record::disp2 }
};
void Record::display()
{
for (size_t i=0; i<sizeof rec/sizeof*rec; ++i)
(this->*(rec[i].disp))();
}
int main()
{
Record r;
r.display();
return 0;
}
Output
Display 1 with a string to display
Display 2 with an integer to display
Compare it to your existing code, and not in particular that pointers to member functions are not simply pointers to functions. They require different handling and generally different operators to utilize. See here for different methods of member access (both variable and function).
Best of luck.
To make the call work you must invoke it like this:
for (int i = 0; i < 2; i++) {
(*rec[i].disp)();
}
And initialize the table this way:
const Record::record Record::rec[] = {
{ 10, &Record::disp1 },
{ 11, &Record::disp2 }
};
I have one application in which following task are to be done
1.) UI application will send command code (integer value).
2.) DLL interface(in c++) will get that integer value and execute corresponding command function.
commands name and command code are maintained as
#define PING 50
there will be 500 commands and applying SWITCH CASE will not sound good. so i decided to implement function pointer in my code as below
#include "stdafx.h"
#include<iostream>
#define PING 20
using namespace std;
//extern const int PING = 10;
void ping()
{
cout<<"ping command executed";
}
void get_status(void)
{
cout<<"Get_status called"<<endl;
}
class ToDoCommands
{
public:
void getCommand( void (*CommandToCall)() );
};
void ToDoCommands::getCommand( void (*CommandToCall)())
{
void (*CommandToCall1)();
CommandToCall1 = CommandToCall;
CommandToCall1();
}
int main()
{
int code;
ToDoCommands obj;
cout<<"enter command code";
cin>>code; // if UI send 50 then Ping function get executed as #define PING 50
obj.getCommand(ping); // here m passing ping manually..
//obj.getCommand(get_status);
return 0;
}
how can i pass command name corresponding to command code in
obj.getCommand(ping);
You are almost there: make a std::map of std::string to function pointer, initialize it with data pairing a string name to a corresponding function pointer, and then use that map at runtime to pick the correct pointer based on the string parameter passed in.
#include <iostream>
#include <string>
#include <map>
using namespace std;
void ping() {
cout << "ping" << endl;
}
void test() {
cout << "test" << endl;
}
int main() {
map<string,void(*)()> m;
m["ping"] = ping;
m["test"] = test;
// I am using hard-coded constants below.
// In your case, strings will come from command line args
m["test"]();
m["ping"]();
return 0;
}
Link to a demo with std::map.
Here is how you can do it without a map (it will be slower because of the linear search, but you can fix it by ordering names alphabetically and using binary search).
#include <iostream>
#include <cstring>
using namespace std;
void ping() {
cout << "ping" << endl;
}
void test() {
cout << "test" << endl;
}
typedef void (*fptr_t)();
int main() {
const fptr_t fptrs[] = {test, ping};
const char *names[] = {"test", "ping"};
const char *fname = "test";
for (int i = 0 ; i != 2 ; i++) {
if (!strcmp(fname, names[i])) {
fptrs[i]();
break;
}
}
return 0;
}
Link to a demo with arrays.
Declare an array of function pointers. Where you treat the index as your "code". For example:
void foo(){
printf("foo\n");
}
void bar(){
printf("bar\n");
}
int main(void)
{
void (*code_to_function[100])();
int code;
code_to_function[0] = foo;
code_to_function[1] = bar;
printf("Enter code: ");
scanf("%d", &code);
code_to_function[code]();
return 0;
}
Please note that for this rudimentary example, inputting integer code other than 0 and 1 will result in a segfault.
I should say #dasblinkenlight is right but if you don't want to use std::map you should implement a map yourself. This can be buggy and not a optimized way, but if you don't want to use STL, it seems you should implement it yourself.
You can use 2 arrays with corresponding indices. One of them is a char * array and another one is function pointers. They are better to be encapsulated in a class named something like MyMap.
class MyMap {
public:
...
inline void add(char *name, (void (*ptr)(void)) ) {
names_[currIndex_] = name; // Or stcpy
ptrs_[currIndex_] = ptr;
currIndex_++;
}
inline (void(*)(void)) get(char *name) {
int foundIndex = -1;
for (int i = 0; i < currIndex_; i++) {
// Find matching index
}
if (foundIndex_ >= 0) {
return ptrs_[foundIndex_];
}
return NULL;
}
private:
int currIndex_;
char *names_[10];
(void (*ptrs_[10])(void));
};