Senin, 21 Juli 2025

<iostream>

Declares objects that control reading from and writing to the standard streams. This include is often the only header you need to do input and output from a C++ program.

Syntax

C++
#include <iostream>

 Note

The <iostream> library uses the #include <ios>, #include <streambuf>, #include <istream>, and #include <ostream> statements.

Remarks

The objects fall into two groups:

  • cin, cout, cerr, and clog are byte oriented, doing conventional byte-at-a-time transfers.

  • wcin, wcout, wcerr, and wclog are wide oriented, translating to and from the wide characters that the program manipulates internally.

Once you do certain operations on a stream, such as the standard input, you can't do operations of a different orientation on the same stream. Therefore, a program can't operate interchangeably on both cin and wcin, for example.

All the objects declared in this header share a peculiar property — you can assume they're constructed before any static objects you define, in a translation unit that includes <iostream>. Equally, you can assume that these objects aren't destroyed before the destructors for any such static objects you define. (The output streams are, however, flushed during program termination.) Therefore, you can safely read from or write to the standard streams before program startup and after program termination.

This guarantee isn't universal, however. A static constructor may call a function in another translation unit. The called function can't assume that the objects declared in this header have been constructed, given the uncertain order in which translation units participate in static construction. To use these objects in such a context, you must first construct an object of class ios_base::Init.

Global Stream Objects

NameDescription
cerrSpecifies the cerr global stream.
cinSpecifies the cin global stream.
clogSpecifies the clog global stream.
coutSpecifies the cout global stream.
wcerrSpecifies the wcerr global stream.
wcinSpecifies the wcin global stream.
wclogSpecifies the wclog global stream.
wcoutSpecifies the wcout global stream.

cerr

The object cerr controls output to a stream buffer associated with the object stderr, declared in <cstdio>.

C++
extern ostream cerr;

Return Value

An ostream object.

Remarks

The object controls unbuffered insertions to the standard error output as a byte stream. Once the object is constructed, the expression cerr.flags & unitbuf is nonzero, and cerr.tie() == &cout. For more details, see cerr.flags and unitbuf.

Example

C++
// iostream_cerr.cpp
// compile with: /EHsc
#include <iostream>
#include <fstream>

using namespace std;

void TestWide( )
{
   int i = 0;
   wcout << L"Enter a number: ";
   wcin >> i;
   wcerr << L"test for wcerr" << endl;
   wclog << L"test for wclog" << endl;
}

int main( )
{
   int i = 0;
   cout << "Enter a number: ";
   cin >> i;
   cerr << "test for cerr" << endl;
   clog << "test for clog" << endl;
   TestWide( );
}

cin

Specifies the cin global stream.

C++
extern istream cin;

Return Value

An istream object.

Remarks

The object controls extractions from the standard input as a byte stream. Once the object is constructed, the call cin.tie returns &cout.

Example

In this example, cin sets the fail bit on the stream when it comes across non-numeric characters. The program clears the fail bit and strips the invalid character from the stream to continue.

C++
// iostream_cin.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;

int main()
{
   int x;
   cout << "enter choice:";
   cin >> x;
   while (x < 1 || x > 4)
   {
      cout << "Invalid choice, try again:";
      cin >> x;
      // not a numeric character, probably
      // clear the failure and pull off the non-numeric character
      if (cin.fail())
      {
         cin.clear();
         char c;
         cin >> c;
      }
   }
}
Output
2

clog

Specifies the clog global stream.

C++
extern ostream clog;

Return Value

An ostream object.

Remarks

The object controls buffered insertions to the standard error output as a byte stream.

Example

See cerr for an example of using clog.

cout

Specifies the cout global stream.

C++
extern ostream cout;

Return Value

An ostream object.

Remarks

The object controls insertions to the standard output as a byte stream.

Example

See cerr for an example of using cout.

wcerr

Specifies the wcerr global stream.

C++
extern wostream wcerr;

Return Value

A wostream object.

Remarks

The object controls unbuffered insertions to the standard error output as a wide stream. Once the object is constructed, the expression wcerr.flags & unitbuf is nonzero. For more details, see wcerr.flags and unitbuf.

Example

See cerr for an example of using wcerr.

wcin

Specifies the wcin global stream.

C++
extern wistream wcin;

Return Value

A wistream object.

Remarks

The object controls extractions from the standard input as a wide stream. Once the object is constructed, the call wcin.tie returns &wcout.

Example

See cerr for an example of using wcin.

wclog

Specifies the wclog global stream.

C++
extern wostream wclog;

Return Value

A wostream object.

Remarks

The object controls buffered insertions to the standard error output as a wide stream.

Example

See cerr for an example of using wclog.

wcout

Specifies the wcout global stream.

C++
extern wostream wcout;

Return Value

A wostream object.

Remarks

The object controls insertions to the standard output as a wide stream.

Example

See cerr for an example of using wcout.

CString instances in a wcout statement must be cast to const wchar_t*, as shown in the following example.

C++
CString cs("meow");

wcout <<(const wchar_t*) cs <<endl;



Sabtu, 19 Juli 2025

Microsoft C++ Union

 #include <queue>


using namespace std;


enum class WeatherDataType

{

    Temperature, Wind

};


struct TempData

{

    int StationId;

    time_t time;

    double current;

    double max;

    double min;

};


struct WindData

{

    int StationId;

    time_t time;

    int speed;

    short direction;

};


struct Input

{

    WeatherDataType type;

    union

    {

        TempData temp;

        WindData wind;

    };

};


// Functions that are specific to data types

void Process_Temp(TempData t) {}

void Process_Wind(WindData w) {}


void Initialize(std::queue<Input>& inputs)

{

    Input first;

    first.type = WeatherDataType::Temperature;

    first.temp = { 101, 1418855664, 91.8, 108.5, 67.2 };

    inputs.push(first);


    Input second;

    second.type = WeatherDataType::Wind;

    second.wind = { 204, 1418859354, 14, 27 };

    inputs.push(second);

}


int main(int argc, char* argv[])

{

    // Container for all the data records

    queue<Input> inputs;

    Initialize(inputs);

    while (!inputs.empty())

    {

        Input const i = inputs.front();

        switch (i.type)

        {

        case WeatherDataType::Temperature:

            Process_Temp(i.temp);

            break;

        case WeatherDataType::Wind:

            Process_Wind(i.wind);

            break;

        default:

            break;

        }

        inputs.pop();


    }

    return 0;

}

================================

// for MyVariant

#include <crtdbg.h>

#include <new>

#include <utility>


// for sample objects and output

#include <string>

#include <vector>

#include <iostream>


using namespace std;


struct A

{

    A() = default;

    A(int i, const string& str) : num(i), name(str) {}


    int num;

    string name;

    //...

};


struct B

{

    B() = default;

    B(int i, const string& str) : num(i), name(str) {}


    int num;

    string name;

    vector<int> vec;

    // ...

};


enum class Kind { None, A, B, Integer };


#pragma warning (push)

#pragma warning(disable:4624)

class MyVariant

{

public:

    MyVariant()

        : kind_(Kind::None)

    {

    }


    MyVariant(Kind kind)

        : kind_(kind)

    {

        switch (kind_)

        {

        case Kind::None:

            break;

        case Kind::A:

            new (&a_) A();

            break;

        case Kind::B:

            new (&b_) B();

            break;

        case Kind::Integer:

            i_ = 0;

            break;

        default:

            _ASSERT(false);

            break;

        }

    }


    ~MyVariant()

    {

        switch (kind_)

        {

        case Kind::None:

            break;

        case Kind::A:

            a_.~A();

            break;

        case Kind::B:

            b_.~B();

            break;

        case Kind::Integer:

            break;

        default:

            _ASSERT(false);

            break;

        }

        kind_ = Kind::None;

    }


    MyVariant(const MyVariant& other)

        : kind_(other.kind_)

    {

        switch (kind_)

        {

        case Kind::None:

            break;

        case Kind::A:

            new (&a_) A(other.a_);

            break;

        case Kind::B:

            new (&b_) B(other.b_);

            break;

        case Kind::Integer:

            i_ = other.i_;

            break;

        default:

            _ASSERT(false);

            break;

        }

    }


    MyVariant(MyVariant&& other)

        : kind_(other.kind_)

    {

        switch (kind_)

        {

        case Kind::None:

            break;

        case Kind::A:

            new (&a_) A(move(other.a_));

            break;

        case Kind::B:

            new (&b_) B(move(other.b_));

            break;

        case Kind::Integer:

            i_ = other.i_;

            break;

        default:

            _ASSERT(false);

            break;

        }

        other.kind_ = Kind::None;

    }


    MyVariant& operator=(const MyVariant& other)

    {

        if (&other != this)

        {

            switch (other.kind_)

            {

            case Kind::None:

                this->~MyVariant();

                break;

            case Kind::A:

                *this = other.a_;

                break;

            case Kind::B:

                *this = other.b_;

                break;

            case Kind::Integer:

                *this = other.i_;

                break;

            default:

                _ASSERT(false);

                break;

            }

        }

        return *this;

    }


    MyVariant& operator=(MyVariant&& other)

    {

        _ASSERT(this != &other);

        switch (other.kind_)

        {

        case Kind::None:

            this->~MyVariant();

            break;

        case Kind::A:

            *this = move(other.a_);

            break;

        case Kind::B:

            *this = move(other.b_);

            break;

        case Kind::Integer:

            *this = other.i_;

            break;

        default:

            _ASSERT(false);

            break;

        }

        other.kind_ = Kind::None;

        return *this;

    }


    MyVariant(const A& a)

        : kind_(Kind::A), a_(a)

    {

    }


    MyVariant(A&& a)

        : kind_(Kind::A), a_(move(a))

    {

    }


    MyVariant& operator=(const A& a)

    {

        if (kind_ != Kind::A)

        {

            this->~MyVariant();

            new (this) MyVariant(a);

        }

        else

        {

            a_ = a;

        }

        return *this;

    }


    MyVariant& operator=(A&& a)

    {

        if (kind_ != Kind::A)

        {

            this->~MyVariant();

            new (this) MyVariant(move(a));

        }

        else

        {

            a_ = move(a);

        }

        return *this;

    }


    MyVariant(const B& b)

        : kind_(Kind::B), b_(b)

    {

    }


    MyVariant(B&& b)

        : kind_(Kind::B), b_(move(b))

    {

    }


    MyVariant& operator=(const B& b)

    {

        if (kind_ != Kind::B)

        {

            this->~MyVariant();

            new (this) MyVariant(b);

        }

        else

        {

            b_ = b;

        }

        return *this;

    }


    MyVariant& operator=(B&& b)

    {

        if (kind_ != Kind::B)

        {

            this->~MyVariant();

            new (this) MyVariant(move(b));

        }

        else

        {

            b_ = move(b);

        }

        return *this;

    }


    MyVariant(int i)

        : kind_(Kind::Integer), i_(i)

    {

    }


    MyVariant& operator=(int i)

    {

        if (kind_ != Kind::Integer)

        {

            this->~MyVariant();

            new (this) MyVariant(i);

        }

        else

        {

            i_ = i;

        }

        return *this;

    }


    Kind GetKind() const

    {

        return kind_;

    }


    A& GetA()

    {

        _ASSERT(kind_ == Kind::A);

        return a_;

    }


    const A& GetA() const

    {

        _ASSERT(kind_ == Kind::A);

        return a_;

    }


    B& GetB()

    {

        _ASSERT(kind_ == Kind::B);

        return b_;

    }


    const B& GetB() const

    {

        _ASSERT(kind_ == Kind::B);

        return b_;

    }


    int& GetInteger()

    {

        _ASSERT(kind_ == Kind::Integer);

        return i_;

    }


    const int& GetInteger() const

    {

        _ASSERT(kind_ == Kind::Integer);

        return i_;

    }


private:

    Kind kind_;

    union

    {

        A a_;

        B b_;

        int i_;

    };

};

#pragma warning (pop)


int main()

{

    A a(1, "Hello from A");

    B b(2, "Hello from B");


    MyVariant mv_1 = a;


    cout << "mv_1 = a: " << mv_1.GetA().name << endl;

    mv_1 = b;

    cout << "mv_1 = b: " << mv_1.GetB().name << endl;

    mv_1 = A(3, "hello again from A");

    cout << R"aaa(mv_1 = A(3, "hello again from A"): )aaa" << mv_1.GetA().name << endl;

    mv_1 = 42;

    cout << "mv_1 = 42: " << mv_1.GetInteger() << endl;


    b.vec = { 10,20,30,40,50 };


    mv_1 = move(b);

    cout << "After move, mv_1 = b: vec.size = " << mv_1.GetB().vec.size() << endl;


    cout << endl << "Press a letter" << endl;

    char c;

    cin >> c;

}

============

Microsoft C++ Class

 // class.cpp

// compile with: /EHsc

// Example of the class keyword

// Exhibits polymorphism/virtual functions.


#include <iostream>

#include <string>

using namespace std;


class dog

{

public:

   dog()

   {

      _legs = 4;

      _bark = true;

   }


   void setDogSize(string dogSize)

   {

      _dogSize = dogSize;

   }

   virtual void setEars(string type)      // virtual function

   {

      _earType = type;

   }


private:

   string _dogSize, _earType;

   int _legs;

   bool _bark;


};


class breed : public dog

{

public:

   breed( string color, string size)

   {

      _color = color;

      setDogSize(size);

   }


   string getColor()

   {

      return _color;

   }


   // virtual function redefined

   void setEars(string length, string type)

   {

      _earLength = length;

      _earType = type;

   }


protected:

   string _color, _earLength, _earType;

};


int main()

{

   dog mongrel;

   breed labrador("yellow", "large");

   mongrel.setEars("pointy");

   labrador.setEars("long", "floppy");

   cout << "Cody is a " << labrador.getColor() << " labrador" << endl;

}

Microsoft C++ Struct

 #include <iostream>

using namespace std;


struct PERSON {   // Declare PERSON struct type

    int age;   // Declare member types

    long ss;

    float weight;

    char name[25];

} family_member;   // Define object of type PERSON


struct CELL {   // Declare CELL bit field

    unsigned short character  : 8;  // 00000000 ????????

    unsigned short foreground : 3;  // 00000??? 00000000

    unsigned short intensity  : 1;  // 0000?000 00000000

    unsigned short background : 3;  // 0???0000 00000000

    unsigned short blink      : 1;  // ?0000000 00000000

} screen[25][80];       // Array of bit fields


int main() {

    struct PERSON sister;   // C style structure declaration

    PERSON brother;   // C++ style structure declaration

    sister.age = 13;   // assign values to members

    brother.age = 7;

    cout << "sister.age = " << sister.age << '\n';

    cout << "brother.age = " << brother.age << '\n';


    CELL my_cell;

    my_cell.character = 1;

    cout << "my_cell.character = " << my_cell.character;

}

// Output:

// sister.age = 13

// brother.age = 7

// my_cell.character = 1

Program C++ BAB XI

 CONTOH 1 : DFS

#include <iostream>

#include <conio>


class vertex

{

      public:

      char lab;

      bool condition;

      vertex *parent;


    vertex(char l)

    {

    lab=l;

    }

};



class graph

{

      public:

         vertex** addvertex;

         int **add_jacent;

         void Addvertex(char a);

         void addedge(int st, int end);

         void ALL_DFS();


    graph()

    {

        addvertex=new vertex*[20];

        add_jacent=new int*[20];

        for(int i=0;i<20;i++)

        {

            add_jacent[i]=new int[20];

            for(int j=0;j<20;j++)

            {

                add_jacent[i][j]=0;

            }

        }

        nvert=0;

    }


     private:

          void display(int v);

          int nvert;

         void DFS_search(vertex *v, int j);

};


void graph::Addvertex(char a)

{

      addvertex[nvert++]=new vertex(a);

}


void graph::addedge(int st, int end)

{

add_jacent[st][end]=1;

add_jacent[end][st]=1;

}


void graph::display(int v)

{

   cout<<addvertex[v]->lab<<" ";

}


void graph::ALL_DFS()

{

   cout<<"Pencarian jalur dengan metode DFS :"<<endl;

   for(int i=0;i<nvert;i++)

   {

       addvertex[i]->condition=false; /// kondisi

       addvertex[i]->parent=NULL; /// keadaan awal

   }


   for(int j=0;j<nvert;j++)

   {

        if(addvertex[j]->condition == false)

        {

          DFS_search(addvertex[j],j);

        }

   }

}


void graph::DFS_search(vertex *vert,int index)

{

   vert->condition=true;

   display(index);


   for(int i=0;i<nvert;i++)

   {

        if((add_jacent[index][i]==1) && (addvertex[i]->condition == false))

        {

            addvertex[i]->parent=vert;

            DFS_search(addvertex[i],i);

        }

   }

}


void main()

{

        graph *a=new graph();


        a->Addvertex('A');   ///0

        a->Addvertex('B');   ///1

        a->Addvertex('C');   ///2

        a->Addvertex('D');   ///3

        a->Addvertex('E');   ///4

        a->Addvertex('F');   ///5

        a->Addvertex('G');   ///6

        a->Addvertex('H');   ///7

        a->Addvertex('I');   ///8

        a->Addvertex('J');   ///9

        a->Addvertex('K');   ///10



        a->addedge(0, 1);  ///AB

        a->addedge(0, 2);  ///AC

        a->addedge(1, 3);  ///BD

        a->addedge(1, 4); ///BE

        a->addedge(2, 5); ///CF

        a->addedge(2, 6); ///CG

        a->addedge(3, 7); ///DH

        a->addedge(3, 8); ///DI

        a->addedge(4, 9);  ///EJ

        a->addedge(5, 10);  ///FK


     a->ALL_DFS();

     cout<<endl;

     cout<<endl;

     cout<<"Hasil Pencarian DFS, sesuai dengan Graph pada Gambar 11.3"<<endl;

  getch();

}

===================================

CONTOH 2 : DFS KOTA

#include <iostream>

#include <conio>

//#include <cstring>

#include <string>


class vertex

{

      public:

      char lab;

      string kota;

      bool condition;

      vertex *parent;


    vertex(char l, string k)

    {

    lab=l;

      kota=k;

    }

};



class graph

{

      public:

         vertex** addvertex;

         int **add_jacent;

         void Addvertex(char a, string kota);

         void addedge(int st, int end);

         void ALL_DFS();


    graph()

    {

        addvertex=new vertex*[20];

        add_jacent=new int*[20];

        for(int i=0;i<20;i++)

        {

            add_jacent[i]=new int[20];

            for(int j=0;j<20;j++)

            {

                add_jacent[i][j]=0;

            }

        }

        nvert=0;

    }


     private:

          void display(int v);

          int nvert;

         void DFS_search(vertex *v, int j);

};


void graph::Addvertex(char a, string k)

{

      addvertex[nvert++]=new vertex(a,k);

}


void graph::addedge(int st, int end)

{

add_jacent[st][end]=1;

add_jacent[end][st]=1;

}


void graph::display(int v)

{

   cout<<addvertex[v]->lab<<" "<<addvertex[v]->kota<<" -->";

}


void graph::ALL_DFS()

{

   cout<<"Pencarian jalur dengan metode DFS :"<<endl;

   for(int i=0;i<nvert;i++)

   {

       addvertex[i]->condition=false; /// kondisi

       addvertex[i]->parent=NULL; /// keadaan awal

   }


   for(int j=0;j<nvert;j++)

   {

        if(addvertex[j]->condition == false)

        {

          DFS_search(addvertex[j],j);

        }

   }

}


void graph::DFS_search(vertex *vert,int index)

{

   vert->condition=true;

   display(index);


   for(int i=0;i<nvert;i++)

   {

        if((add_jacent[index][i]==1) && (addvertex[i]->condition == false))

        {

            addvertex[i]->parent=vert;

            DFS_search(addvertex[i],i);

        }

   }

}


void main()

{

        graph *a=new graph();


        a->Addvertex('A',"Mataram");   ///0

        a->Addvertex('B',"Jalan Lingkar");   ///1

        a->Addvertex('C',"Patung Giri menang");   ///2

        a->Addvertex('D',"Perbatasan Lombar-Loteng");   ///3

        a->Addvertex('E',"BIL");   ///4

        a->Addvertex('F',"Tanah Awu");   ///5

        a->Addvertex('G',"Rembitan");   ///6

        a->Addvertex('H',"Sade");   ///7

        a->Addvertex('I',"Tanjung Aan");   ///8

        a->Addvertex('J',"Kute");   ///9



        a->addedge(0, 1);  ///AB

        a->addedge(0, 6);  ///AD

        a->addedge(1, 2);  ///BC

        a->addedge(1, 3); ///BD

        a->addedge(6, 7); ///CG

        a->addedge(2, 4); ///CF

        a->addedge(2, 3); ///CD

        a->addedge(3, 4); ///DE

        a->addedge(3, 5);  ///EF

        a->addedge(4, 5);  ///EH

        a->addedge(7, 8); ///FH

        a->addedge(7, 9); ///GH

        a->addedge(8, 9); ///GI


     a->ALL_DFS();


  getch();

}




==============================================

CONTOH 3 : DIJSKTRA

#include <iostream>

#include <conio>

#include <string>


class vertex

{

    public:

        char lab;

         vertex *parent;

         int distance;

         bool value;


    vertex(char a)

    {

    lab=a;

    }

};


class edge

{

    public:

       int vert;

         int weight;


    edge(int v,int w)

    {

    vert=v;

      weight=w;

    }

};


class PQ

{

public:

      int size;

      edge **add_edge;

      int top;


      PQ(int i, int x)

      {

      size=i;

            add_edge=new edge*[size];

      top=x;

      }


int isempty()

      {

             if(top<=0)

    return 1;

             else

    return 0;

    }



void insert(edge *item)

      {

         if(isempty()==1)

        {

                add_edge[top++]=item;

        }else

          {

               int step=0;

               int i;

               for(i=0;i<top;i++)

               {

                     if((add_edge[i]->vert) == (item->vert) )

                     {

                     step=1;

                         int ganti=item->weight;

                           if((add_edge[i]->weight) >= ganti)

                           {

                        add_edge[i]->weight=ganti;

                        break;

                           }

                    }else if((add_edge[i]->weight) >= (item->weight))

                   {

                     break;

                   }

            }


            if(step==0)

            {

                for(int j=top;j>i;j--)

               {

                add_edge[j]=add_edge[j-1];

               }

              add_edge[i]=item;

              top++;

            }

     }

  }


edge* pop()

{

      edge *temp;

    if(isempty()==1)

      {

          cout<<"kosong";

      }else

      {

            temp=add_edge[0];

            for(int i=1;i<top;i++)

           {

                add_edge[i-1]=add_edge[i];

            }

            top--;

      }

      return temp;

}

};



class graph

{

public:

     void Addvertex(char v);

      void addedge(int s,int e,int w);

      void Djikstra();


    graph()

    {

        addvertex=new vertex*[20];

        add_adjacent=new int*[20];

        for(int i=0;i<20;i++)

        {

          add_adjacent[i]=new int[20];

            for(int j=0;j<20;j++)

            {

                add_adjacent[i][j]=0;

            }

        }


        Q=new PQ(200,0);

        addjacent=0;

        nvert=0;

    }


    private:

        void displayvert(vertex *v);

        void relaxation(int st,int end,int dist);

        vertex **addvertex;

        int **add_adjacent;

       PQ *Q;

       int addjacent;

       int nvert;

};


void graph::Addvertex(char lab)

{

   addvertex[nvert++]=new vertex(lab);

}



void graph::addedge(int st, int end, int w)

{

   this->add_adjacent[st][end]=w;

   addjacent++;

}



void graph::displayvert(vertex *disp)

{

    if(disp->parent != NULL)

    {

    displayvert(disp->parent);

      cout<<disp->lab<<" ";

    }

}



void graph::relaxation(int st,int end,int dist)

{

   int destination=addvertex[end]->distance;

   int start=addvertex[st]->distance;


   if(destination > (start+dist))

   {

    addvertex[end]->distance=start+dist;

    addvertex[end]->parent=addvertex[st];

   }

}



void graph::Djikstra()

{

    for(int i=0;i<nvert;i++)

   {

      addvertex[i]->distance=99;

      addvertex[i]->parent=NULL;

      addvertex[i]->value=false;

   }


   int current=0;

   addvertex[0]->distance=0;


   edge *start=new edge(current,0);

   Q->insert(start);


   while(Q->isempty() !=1 )

   {

        addvertex[current]->value=true;

        for(int j=0;j<nvert;j++)

       {

         if(j==current)

          continue;


         if(addvertex[j]->value==true)

          continue;


         int dist=add_adjacent[current][j];


         if(dist==0)

          continue;


         relaxation(current,j,dist);

         int weight=addvertex[j]->distance;


         edge *path=new edge(j,weight);

        Q->insert(path);

        }


        edge *pop=Q->pop();

        current=pop->vert;

        int w=pop->weight;

   }


      for(int i=0;i<nvert;i++)

      {

         cout<<"Biaya untuk ke vertex "<<addvertex[i]->lab<<" :"

            <<addvertex[i]->distance<<endl;

         cout<<"Jalur :";

         displayvert(addvertex[i]);

         cout<<" "<<endl;

      }

}



void main()

{

        graph *a=new graph();

      /*

         a->Addvertex('A');      ///0

         a->Addvertex('B');      ///1

         a->Addvertex('C');      ///2

         a->Addvertex('D');      ///3

         a->Addvertex('E');      ///4

         a->Addvertex('F');      ///5

         a->Addvertex('G');      ///6

         a->Addvertex('H');      ///7

         a->Addvertex('I');      ///8

         a->Addvertex('J');      ///9



         a->addedge(0,1,2); ///AB

         a->addedge(0,2,12); ///AC

         a->addedge(0,4,6); ///AE

         a->addedge(1,3,1); ///BD

         a->addedge(1,4,3); ///BE

         a->addedge(2,8,3); ///CI

         a->addedge(3,4,1); ///DE

         a->addedge(3,5,7); ///DF

         a->addedge(3,7,5); ///DH

         a->addedge(4,2,2); ///EC

         a->addedge(4,8,6); ///EI

         a->addedge(4,6,9); ///EG

         a->addedge(6,7,5); ///GH

         a->addedge(6,9,2); ///GJ

         a->addedge(7,5,1); ///HF

         a->addedge(7,9,2); ///HJ

         a->addedge(8,6,1); ///IG

a->addedge(8,9,6); ///IJ


         */

         a->Addvertex('A');      ///1

         a->Addvertex('B');      ///2

         a->Addvertex('C');      ///3

         a->Addvertex('D');      ///4

         a->Addvertex('E');      ///5

         a->Addvertex('F');      ///6


         a->addedge(0,1,10); ///AB

         a->addedge(0,2,5); ///AC

         a->addedge(1,2,2); ///BC

         a->addedge(1,3,1); ///BD

         a->addedge(2,1,3); ///CB

         a->addedge(2,3,9); ///CD

         a->addedge(2,4,2); ///CE

         a->addedge(3,4,2); ///DE

         a->addedge(3,5,12); ///DF

         a->addedge(4,0,7); ///EA

         a->addedge(4,3,6); ///ED

         a->addedge(4,5,15); ///EF



         cout<<"Implementasi Algoritma Djikstra :"<<endl;

         cout<<endl;

         a->Djikstra();


       getch();

} 

=================================================

CONTOH 4 : KRUSKAL

#include <iostream>

#include <conio>

#include <string>


class vertex

{

    public:

    char lab;

      string kota;

vertex *parent;

      int rank;


       vertex(char l,string k)

      {

  lab=l;

         kota=k;

      }

};


class edge

{

    public:

    int start;

      int weight;

      int end;


   edge(int s,int e,int w)

   {

      start=s;

      end=e;

      weight=w;

   }

};


class PQ

{

public:

      int size;

      edge **add_edge;

      int top;


      PQ(int i, int x)

      {

  size=i;

      add_edge=new edge*[size];

  top=x;

      }


   int isempty()

   {

        if(top<=0)

    return 1;

        else

    return 0;

   }


  void insert(edge *item)

  {


       if(isempty()==1)

      {

          add_edge[top++]=item;


      }else

      {

            int i;

            for(i=0;i<top;i++)

            {

                if(add_edge[i]->weight>=item->weight)

                 break;

            }


            for(int j=top;j>i;j--)

            {

                add_edge[j]=add_edge[j-1];

            }

            add_edge[i]=item;

            top++;

       }

   }

};



class graph

{

public:

      vertex **addvertex;

      int **add_adjacent;

            int nvert,addjacent;


    void Addvertex(char v,string kota);

      void addedge(int s,int e,int w);

      void kruskal();


    graph()

    {

        addvertex=new vertex*[20];

        add_adjacent=new int*[20];

        for(int i=0;i<20;i++)

        {

             add_adjacent[i]=new int[20];

                 for(int j=0;j<20;j++)

                {

                add_adjacent[i][j]=1000000;

                }

        }

          x=new PQ(200,0);

         nvert=0;

         addjacent=0;

    }




    private:

      void makeset(vertex *v);

      void displayvert(int v);

            void displayvertex(int v);

      vertex *findset(vertex *v);

      void uni(vertex *x,vertex *y);

      void link(vertex *x,vertex *y);

            PQ *x;


};


void graph::Addvertex(char lab, string k)

{

   addvertex[nvert++]=new vertex(lab,k);

}


void graph::addedge(int st, int end, int w)

{

   this->add_adjacent[st][end]=w;

   this->add_adjacent[end][st]=w;

   addjacent++;


edge *path=new edge(st,end,w);

    x->insert(path);

}


void graph::displayvert(int v)

{

   cout<<addvertex[v]->kota;

}


void graph::displayvertex(int v)

{

   cout<<addvertex[v]->lab<<"";

}


void graph::makeset(vertex *v)

{

     v->parent=v;

     v->rank=0;

}



vertex* graph::findset(vertex *v)

{

   if(v != v->parent)

   {

       v->parent=findset(v->parent);

   }

   return v->parent;

}


void graph::link(vertex *x, vertex *y)

{

    if(x->rank > y->rank)

    {

    y->parent=x;

    }else

    {

    x->parent=y;

      if(x->rank == y->rank)

      y->rank=y->rank+1;

    }

}


void graph::uni(vertex *x, vertex *y)

{

   link(findset(x),findset(y));

}


void graph::kruskal()

{

    int total=0;

    for(int i=0;i<nvert;i++)

   {

      makeset(addvertex[i]);

   }


   for(int i=0;i<addjacent;i++)

   {

    int start=x->add_edge[i]->start;

    int end=x->add_edge[i]->end;


      vertex *a;

                     a=findset(addvertex[start]);

      vertex *b;

      b=findset(addvertex[end]);


      if(a->lab != b->lab)

      {

          uni(addvertex[start], addvertex[end]);

          displayvert(start);

          cout<<"-";

          displayvert(end);

          cout<<"(";

          displayvertex(start);

          displayvertex(end);

          cout<<")";

     //     cout<<add_adjacent[start][end]<<" ";


          total=total+this->add_adjacent[start][end];

      }


   }

   cout<<endl;

   cout<<"Nilai Total keseluruhan MST :"<<total;

}


void main()

{

      cout<<"Implementation of Graph using Kruskal Algorithm "<<endl;

graph *a=new graph();


        a->Addvertex('A',"dompu");   ///0

        a->Addvertex('B',"Mataram");   ///1

        a->Addvertex('C',"denpasar");   ///2

        a->Addvertex('D',"banyuwangi");   ///3

        a->Addvertex('E',"surabaya");   ///4

        a->Addvertex('F',"Yogyakarta");   ///5

        a->Addvertex('G',"semarang");   ///6

        a->Addvertex('H',"Jakarta");   ///7

        a->Addvertex('I',"Bandung");   ///8


        a->addedge(0, 1, 6);  ///AB

        a->addedge(0, 3, 8);  ///AD

        a->addedge(1, 2, 1);  ///BC

        a->addedge(1, 3, 10); ///BD

        a->addedge(2, 6, 20); ///CG

        a->addedge(2, 5, 15); ///CF

        a->addedge(2, 3, 21); ///CD

        a->addedge(3, 4, 14); ///DE

        a->addedge(4, 5, 3);  ///EF

        a->addedge(4, 7, 5);  ///EH

        a->addedge(5, 7, 11); ///FH

        a->addedge(6, 7, 13); ///GH

        a->addedge(6, 8, 18); ///GI

        a->addedge(7, 8, 17);  ///HI


        a->kruskal();

        getch();


}