Showing posts with label c. Show all posts
Showing posts with label c. Show all posts

Thursday, November 3, 2016

Creating a templated Binary Search Tree Class in C

Creating a basic template Tree Class in C++
(Works in Linux and Windows)

If you just want the code and not the walkthrough, it is attached at the end (I use the GNU GPL license, so do whatever you want with the code as long as you mention me).

There a multiple benefits of creating a Tree class based on a template. With a template, the tree can be a container for anything while still being fairly clean code. We will also create this class to be easily inherited for other trees such as an AVL and Huffman tree (which we will implement later).

A tree is a widely used data structure which organizes a set of nodes containing data. More can be found on it here: http://en.wikipedia.org/wiki/Tree_%28data_structure%29

This tree will be a Binary Search Tree; however, it will be easily inheritable so that other trees (Binary trees, such as AVL and Red-Black) can be defined based on it.

First we will set up our Node as a holder for the data and tree information such as the parent and connected nodes (the leaves). I overload the < operator so that we can search and sort this tree using the c++ algorithm include if we so desire.

template <class T>
class Node {
public:
    T data;
    Node *left, *right, *parent;

    Node() {
        left = right = parent = NULL;
    };
    Node(T &value) {
        data = value;
    };
    ~Node() {
    };   
    void operator= (const Node<T> &other) {
        data = other.data;
    };
    bool operator< (T &other) {
        return (data < other);
    };
};

Our tree will basically just be a bunch of these Nodes pointing to each other, with some functions to manage the data structure.

template <class T>
class Tree {
public:
    Tree() {
        root = NULL;
    };

    ~Tree() {
        m_destroy(root);
    };

    //We will define these all as virtuals for inherited trees (like a Huffman Tree and AVL Tree shown later)
    virtual void insert(T &value) {
        m_insert(root,NULL,value);
    };
    virtual Node<T>* search(T &value) {
        return m_search(root,value);
    };
    virtual bool remove(T &value) {
        return m_remove(root,value);
    };
    virtual bool operator< (Tree<T> &other) {
        return (root->data < other.first()->data);
    };
    void operator= (Tree<T> &other) {
        m_equal(root,other.first());
    };
    Node<T>*& first() {
        return root;
    };


protected:
    //this will be our root node and private functions
    Node<T> *root;
    void m_equal(Node<T>*& node, Node<T>* value) {
        if(value != NULL) {
            node = new Node<T>();
            *node = *value;
            if(value->left != NULL)
                m_equal(node->left, value->left);
            if(value->right != NULL)
                m_equal(node->right, value->right);
        }
    }

    void m_destroy(Node<T>* value) {
        if(value != NULL) {
            m_destroy(value->left);
            m_destroy(value->right);
            delete value;
        }
    };
    void m_insert(Node<T> *&node, Node<T> *parent, T &value) {
        if(node == NULL) {
            node = new Node<T>();
            *node = value;
            node->parent = parent;
        } else if(value < node->data) {
            m_insert(node->left,node,value);
        } else
            m_insert(node->right,node,value);
    };
    void m_insert(Node<T> *&node, Node<T> *parent, Tree<T> &tree) {
        Node<T> *value = tree.first();
        if(node == NULL) {
            node = new Node<T>();
            *node = *value;
            node->parent = parent;
        } else if(value->data < node->data) {
            m_insert(node->left,tree);
        } else
            m_insert(node->right,tree);
    };
    Node<T>* m_search(Node<T> *node, T &value) {
        if(node == NULL)
            return NULL;
        else if(value == node->data)
            return node;
        else if(value < node->data)
            return m_search(node->left,value);
        else
            return m_search(node->right,value);
    };

    bool m_remove(Node<T> *node, T &value) {
        //messy, need to speed this up later
        Node<T> *tmp = m_search(root,value);
        if(tmp == NULL)
            return false;
        Node<T> *parent = tmp->parent;
        //am i the left or right of the parent?
        bool iamleft = false;
        if(parent->left == tmp)
            iamleft = true;
        if(tmp->left != NULL && tmp->right != NULL) {
            if(parent->left == NULL || parent->right == NULL) {
                parent->left = tmp->left;
                parent->right = tmp->right;
            } else {
                if(iamleft)
                    parent->left = tmp->left;
                else
                    parent->right = tmp->left;
                T data = tmp->right->data;
                delete tmp;
                m_insert(root,NULL,data);
            }
        } else if(tmp->left != NULL) {
            if(iamleft)
                parent->left = tmp->left;
            else
                parent->right = tmp->left;
        } else if(tmp->right != NULL ) {
            if(iamleft)
                parent->left = tmp->right;
            else
                parent->right = tmp->right;
        } else {
            if(iamleft)
                parent->left = NULL;
            else
                parent->right = NULL;
        }
        return true;
    };
};

And thats all we need for a basic binary search tree. The full code is shown below

Tree.h 

Consider donating to further my tinkering.


Places you can find me
Read More..

Monday, August 29, 2016

Using the Google Voice C API

First of all, this obviously isnt an official Google API. I wrote it because I wanted one in C++ and couldnt find one that worked.

That being said, the code is on github here (in the TextCommand folder) and is available under GPLv3 for anyone to use.
I know this could (maybe even should) have its own github project but since I use it for my home automation projects, its included in the PiAUISuite. That being said, the current gvapi binary is also compiled for the Pi. So you will need to run make gvapi if you want to use it on any other linux machine.

To include the C++ code in your own project, you just need to include gvoice.h in your file and then you should be able to access the GoogleVoice class. An excellent example to look at is gvapi.cpp since it shows how to interact with it. You should need only to call Init and Login, then you should be able to do any of the Google voice functions.

If you only to use gtextcommand to send commands to your pi, see here. If you want to send or check SMS without having to include the source in your code/project, just use the gvapi program. It can get contacts, send, receive, and delete SMS. It also comes in with built in spoof protection (this is included in GoogleVoice::CheckSMS).

Heres a quick video demo as an example of the kinds of things you can do with gvapi


Using the gvapi program is fairly simple and its man page is below:


gvapi


gvapi - Use of Google voice API in order to send and receive SMS  

SYNOPSIS

gvapi [OPTIONS]...  

DESCRIPTION

gvapi was compiled for use with home automation on the Raspberry Pi but will work on any linux system with an internet connection. It uses curl and boost regex in order to login and stores the cookie in /dev/shm. It only logs in once every 24 hours to save time. It supports a multitude of different options and parameters. For help/comments/questions, feel free to e-mail me at help@stevenhickson.com. I answer sporadically but do eventually respond.
 

OPTIONS

-?
Same as -h
-c
Checks your incoming text messages to see if you have anything unread. It will mark it whatever it outputs as read unless you also use the -r flag. If you include a number with the -n flag, you can specify it to only check messages received from that number. You can also use the -k flag to specify that the message must start with a certain keyword.
-d
Sets debug mode on. You can also specify debug mode from 1 - 3, where 3 is the most verbose.
Ex: gvapi -c -d2
-h
Asks for some quick general use help for gvapi.
-i
Outputs the contacts of your google voice account in the form name==number
-k KEYWORD
Sets a keyword that has to be in the beginning of the text message for it to be returned. This is useful as a password for parsing only certain messages.
-m MESSAGE
Sends the message you specify. This should be in quotes if it contains special characters or a space. The number also has to be specified otherwise it wont have a message to send
Ex: gvapi -n +15551234 -m Hello
-n NUMBER
Can be used with the -c flag to check messages from a certain number or the -m flag to send a message. Can be in a format without the country code, with just the country code, or with a plus sign and the country code. If the formost, it interprets it as a US number.
Ex: gvapi -n 5551234 -c
-p PASSWORD
Can be used with the -u flag to log in manually. If not specified, the program uses the default username and password specified in ~/.gv
-r
Receives and deletes SMS messges. Can be used with the -c flag or without. It is the same as the -c flag but instead of just marking the messages as read. It deletes them.
-u USERNAME
Can be used with the -p flag to log in manually. See the -p flag for more details. Cannot be used without the -p flag.
-v
Outputs version and creater information

AUTHOR

Steven Hickson (help@stevenhickson.com)  

BUGS

No known bugs. To report bugs, send a clear description to help@stevenhickson.comSince this program is fairly crude, user typos could cause crashes/failed responses. Please read the man page thoroughly before submitting a bug.  

COPYRIGHT

Copyright © 2013 Steven Hickson. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it as long as you give credit to the author and include this license. There is NO WARRANTY, to the extent permitted by law.  

HISTORY

This is the second major version of this program  

SEE ALSO

http://stevenhickson.blogspot.com/

Consider donating to further my tinkering.


Places you can find me
Read More..

Monday, September 22, 2014

A C PROGRAM TO PRINT HELLO WORLD WITHOUT USING SEMICOLON

using if

main()
{
if(printf("Hello World")){
}}



using switch


main()
{
switch(printf("Hello World")){
}}



using while


main()
{
while(!printf("Hello World")){
}}


                                            TRY THIS

Read More..

Tuesday, July 15, 2014

How to Create a Header File in C

Although a C++ programmer can use a header file to include any type of code in another file prior to compilation, they mainly use them to define a class. Typically programmers define a class interface in a header file and then write all of the class internal code in a separate source code file. In this way other programmers making use of the class directly or as part of a library need only the header file to inform themselves and the compiler how to use it. A simple class interface defined in a C++ header file can serve as both an example and a template for much larger more complex classes later.

Instructions

Things Youll Need:

  • Text or Code Editor

    Creating a Header File

  1. Step 1

    Create a new file named "MyClass.h." Enter the following three lines at the top of the file:

    #ifndef _MYCLASS
    #define _MYCLASS
    #endif

    The class will be defined between the line beginning with #define and the one beginning with #endif. These are preprocessor directives which tell the compiler to skip inclusion of this files contents if _MYCLASS has already been defined. If _MYCLASS is undefined, the compiler will define it and proceed to include the rest of the file. This prevents you from accidentally including a header file more than once, which can lead to conflicts and errors.

  2. Step 2

    Enter the following two lines after the line beginning with #define:

    #include
    using std::string;

    This example class requires a string data type. The first directive includes the header file for the string class; the second statement simplifies its use by telling the compiler which namespace to make available. Rather than typing "std::string" everywhere, you use a string you can just type "string."

  3. Step 3

    Enter the following before the line with the #endif directive:

    class MyClass
    {
    };

    This defines an empty class.

  4. Step 4

    Fill the empty class by inserting the following lines within the opening and closing brackets:

    public:
    MyClass(string val);
    void setVal(string val);
    string getVal();
    private:
    string _myDataMember;

    You have added one private class data member of type string and three public class method declarations: a constructor and two methods for accessing the data member. Task complete; class interface defined; C++ header file created. Most header files you will create or encounter will simply be more complex variations of this example

Read More..

Saturday, April 5, 2014

C APTITUDES


  •  class Sample

{
public:
        int *ptr;
        Sample(int i)
        {
        ptr = new int(i);
        }
        ~Sample()
        {
        delete ptr;
        }
        void PrintVal()
        {
        cout << "The value is " << *ptr;
        }
};
void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
}
int main()
{
Sample s1= 10;
SomeFunc(s1);
s1.PrintVal();
}
Answer:
Say i am in someFunc
Null pointer assignment(Run-time error)
Explanation:
As the object is passed by value to SomeFunc  the destructor of the object is called when the control returns from the function. So when PrintVal is called it meets up with ptr  that has been freed.The solution is to pass the Sample object  byreference to SomeFunc:

void SomeFunc(Sample &x)
{
cout << "Say i am in someFunc " << endl;
}
because when we pass objects by refernece that object is not destroyed. while returning from the function.

  •                 Which is the parameter that is added to every non-static member function when it is called?

Answer:
            ‘this’ pointer

  •           class base

        {
        public:
        int bval;
        base(){ bval=0;}
        };

class deri:public base
        {
        public:
        int dval;
        deri(){ dval=1;}
        };
void SomeFunc(base *arr,int size)
{
for(int i=0; i<size; i++,arr++)
        cout<<arr->bval;
cout<<endl;
}

int main()
{
base BaseArr[5];
SomeFunc(BaseArr,5);
deri DeriArr[5];
SomeFunc(DeriArr,5);
}

Answer:
 00000
 01010
Explanation:  
The function SomeFunc expects two arguments.The first one is a pointer to an array of base class objects and the second one is the sizeof the array.The first call of someFunc calls it with an array of bae objects, so it works correctly and prints the bval of all the objects. When Somefunc is called the second time the argument passed is the pointeer to an array of derived class objects and not the array of base class objects. But that is what the function expects to be sent. So the derived class pointer is promoted to base class pointer and the address is sent to the function. SomeFunc() knows nothing about this and just treats the pointer as an array of base class objects. So when arr++ is met, the size of base class object is taken into consideration and is incremented by sizeof(int) bytes for bval (the deri class objects have bval and dval as members and so is of size >= sizeof(int)+sizeof(int) ).

  •        class base

        {
        public:
            void baseFun(){ cout<<"from base"<<endl;}
        };
 class deri:public base
        {
        public:
            void baseFun(){ cout<< "from derived"<<endl;}
        };
void SomeFunc(base *baseObj)
{
        baseObj->baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
deri deriObject;
SomeFunc(&deriObject);
}
Answer:
            from base
            from base
Explanation:
            As we have seen in the previous case, SomeFunc expects a pointer to a base class. Since a pointer to a derived class object is passed, it treats the argument only as a base class pointer and the corresponding base function is called.

  •         class base

        {
        public:
            virtual void baseFun(){ cout<<"from base"<<endl;}
        };
 class deri:public base
        {
        public:
            void baseFun(){ cout<< "from derived"<<endl;}
        };
void SomeFunc(base *baseObj)
{
        baseObj->baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
deri deriObject;
SomeFunc(&deriObject);
}
Answer:
            from base
            from derived
Explanation:
            Remember that baseFunc is a virtual function. That means that it supports run-time polymorphism. So the function corresponding to the derived class object is called.
           

  •         void main()

{
            int a, *pa, &ra;
            pa = &a;
            ra = a;
            cout <<"a="<<a <<"*pa="<<*pa <<"ra"<<ra ;
}
/*
Answer :
            Compiler Error: ra,reference must be initialized
Explanation :
            Pointers are different from references. One of the main
differences is that the pointers can be both initialized and assigned,
whereas references can only be initialized. So this code issues an error.
*/

  •   const int size = 5;

void print(int *ptr)
{
            cout<<ptr[0];
}

void print(int ptr[size])
{
            cout<<ptr[0];
}

void main()
{
            int a[size] = {1,2,3,4,5};
            int *b = new int(size);
            print(a);
            print(b);
}
/*
Answer:
            Compiler Error : function void print(int *) already has a body

Explanation:
            Arrays cannot be passed to functions, only pointers (for arrays, base addresses)
can be passed. So the arguments int *ptr and int prt[size] have no difference 
as function arguments. In other words, both the functoins have the same signature and
so cannot be overloaded.
*/

  •      class some{

public:
            ~some()
            {
                        cout<<"somes destructor"<<endl;
            }
};

void main()
{
            some s;
            s.~some();
}
/*
Answer:
            somes destructor
            somes destructor
Explanation:
            Destructors can be called explicitly. Here s.~some() explicitly calls the
destructor of s. When main() returns, destructor of s is called again,
hence the result.
*/

Read More..
 
Copyright 2009 Information Blog
Powered By Blogger