2014 dxdy logo

Научный форум dxdy

Математика, Физика, Computer Science, Machine Learning, LaTeX, Механика и Техника, Химия,
Биология и Медицина, Экономика и Финансовая Математика, Гуманитарные науки




На страницу 1, 2  След.
 
 [C++]неориентированный граф
Сообщение14.05.2012, 12:26 
Здравствуйте!
Используя методы объектно-ориентированного программирования требуется реализовать абстрактную структуру данных (класс), называемую «граф»(G(V,E))
Для выполнения базовых операций над графами требуется реализовать следующие методы класса (операторы):
AddVertex (v1) – добавление вершины к графу G, в случае существования в составе G указанной вершины должно выдаваться соответствующее уведомление;
AddEdge (v1,v2) – соединение двух вершин ребром, если указанные вершины на момент выполнения указанной операции уже смежны, то оператору должен быть оповещён о данном факте;
DelVertex (v1) – удаление указанной вершины из графа G, при этом должны удаляться все инцидентные данной вершине рёбра, в случае отсутствия заданной вершины оператору должно выдаваться соответствующее уведомление;
DelEdge (v1,v2) – удаление ребра соединяющего две заданные вершины, в случае отсутствия такого ребра оператору должно выдаваться соответствующее уведомление;
LoadGraph() – загружает граф в память программы из файла;
SaveGraph() – сохраняет созданный в памяти программы граф в файл; -(это всё уже сделано)
остались эти две:

IsFull(G) – анализирует граф на предмет свойства «полнота» и сообщает о соответствующем результате;
D (v,1) – возвращает список вершин, удалённых на расстояние 1 от вершины v.
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

string str(int d)
{
int n = 10;
string s = "";
while(d != 0)
{
s = char(((d%n)/(n/10))+48) + s;
d = d - (d%n);
n *= 10;
}
return s;
}



struct link
{
int data;
link* next;
};


class linklist
{
private:
link* first;
public:
bool e;

linklist ( )
{
first = NULL;
e = false;
}

void additem ( int d );
void linklist::display ( );
bool exist(int x);
void makenull();


};

void linklist::additem ( int d ) // добавление элемента
{
link* newlink = new link; // выделяем память
newlink->data = d; // запоминаем данные
newlink->next = first; // запоминаем значение first
first = newlink; // first теперь указывает на новый элемент
}

void linklist::display ( )
{
link* current = first; // начинаем с первого элемента
while( current ) // пока есть данные
{
cout << current->data << endl; // печатаем данные
current = current->next; // двигаемся к следующему элементу
}
}

bool exist(int x)
{
link* current = first;
if (!current) return 0;
while( current )
{
if (current->data == x)
{
return 1;
break;
}
current = current->next;
}

if (current == NULL)
return 0;
}

void makenull()
{
link* current = first;
link* deleted = new link;
while(!(current))
{
deleted = current;
current = current->next;
delete deleted;
}
first = NULL ;
cout<<"Linklist is free";
}


class Graph
{
private:

linklist adj[1000];

public:

Graph ( )
{ }

void addedge (int x,int y);
void addvertex (int x);
void deledge (int x,int y);
void delvertex (int x);
void load();
void save();



void q(int n);
void d(int x);
void IsFull(G);
void D(v,1);

};


void Graph::addedge(int x,int y)
{
if ((adj[x].e == true) && (adj[y].e == true) && (adj[x].exist(y) == false) && (adj[y].exist(x)==false) && (x!=y))
{
adj[x].additem(y);
adj[y].additem(x);
}
else cout<<"Error"<<endl;
}

void Graph::addvertex(int x)
{

if (adj[x].e==false)
adj[x].e=true;
else
cout<<"Vertise is !!!"<<endl;
}

void Graph::deledge (int x,int y)
{
if ((adj[x].e == true) && (adj[y].e == true) && (adj[x].exist(y) == true) && (adj[y].exist(x) == true) && (x!=y))
{
adj[x].delitem(y);
adj[y].delitem(x);
}
else cout<<"Error"<<endl;
}

void Graph::delvertex(int x)
{
if (adj[x].e == true)
{
adj[x].e = false;
adj[x].makenull();

for (int i = 1; i < 1000; i++)
{
if (adj[i].exist(x) == 1)
adj[i].delitem(x);
}
}
else
cout<<"Vertise is not !!!"<<endl;
}

void Graph::save()
{
string s = "";
for(int i = 1;i <= 1000; i++)
{
if(adj[i].e == true)
{
/*cout<<"save"<<endl;
s = s + str(i) + " - ";
out.write(s.c_str(),s.size());*/
adj[i].save(i);
}
//out.close();
}
}

void Graph::display()
{
for (int i = 1; i < 1000; i++)
{
if (adj[i].e == true)
{
cout<<i<<" - ";
adj[i].display();
cout<<endl;
}
}
}

void Graph::q(int n)
{
int d = 0;
for (int i = 1; i <= n; i++)
{
if (adj[i].e == true)
d = d + adj[i].Putnumberver();
}
cout<<"There are "<<(d/2)<<" edges in the Graph"<<endl;
}

void Graph::d(int x)
{
cout<<"The degree of vertex "<<x<<" is "<<adj[x].Putnumberver()<<endl;
}



}
int main()
{
Graph G;
int n = 0,x = 0,y = 0,v = 0;


while(true)
{

cout<<"What are you want?"<<endl
<<"1 - Add Vertex"<<endl
<<"2 - Add Edge"<<endl
<<"3 - Delete Vertex"<<endl
<<"4 - Delete Edge"<<endl
<<"5 - Calculate the numbers of Edge"<<endl
<<"6 - Calculate the numbers of Vertex"<<endl
<<"7 - Calculate the degree of vertex"<<endl
<<"8 - Display Graph to monitor"<<endl
<<"9 - Save Graph"<<endl
<<"10 - Load Graph"<<endl
<<"11 - Exit"<<endl;
cin>>v;



if(v == 1)
{
cout<<"Enter Vertex"<<endl;
cin>>x;
G.addvertex(x);
n++;
};

if(v == 2)
{
cout<<"Enter edge(vertexes x and y)"<<endl;
cin>>x>>y;
G.addedge(x,y);
};
if(v == 3)
{
cout<<"Enter deleted Vertex"<<endl;
cin>>x;
G.delvertex(x);
};

if(v == 4)
{
cout<<"Enter deleted edge(vertexes x and y)"<<endl;
cin>>x>>y;
G.deledge(x,y);
};

if(v == 5)
{
G.q(n);
};

if(v == 6)
{
G.p(n);
};

if(v == 7)
{
cout<<"Enter Vertex"<<endl;
cin>>x;
G.d(x);
};

if(v == 8)
G.display();

if(v == 9)
{
G.saves();
}

if(v == 10)
{string d = "1111111";
ofstream out("file.txt");
out.write(d.c_str(),d.size());

d = "vgbjrvbrhbr ";

out.write(d.c_str(),d.size());


d = "jfnvrfbjhvbrjdb ";

out.write(d.c_str(),d.size());


d = "vjvhrvuedbrj";

out.write(d.c_str(),d.size());
out.close();



}

if(v == 11)
break;
}




system("pause");
return 0;
}

 
 
 
 Re: [C++]неориентированный граф
Сообщение14.05.2012, 14:59 
Lady000 в сообщении #570680 писал(а):
Здравствуйте!

Попытайтесь исправить синтаксические ошибки, что бы появился предмет обсуждения. Если не получится исправить, задавайте вопрос. С уважением,

 
 
 
 Re: [C++]неориентированный граф
Сообщение14.05.2012, 15:40 
какие синтаксические ошибки?я не совсем поняла...

 
 
 
 Re: [C++]неориентированный граф
Сообщение14.05.2012, 15:53 
Lady000 в сообщении #570749 писал(а):
какие синтаксические ошибки?


О которых сообщает компилятор. У меня Builder6. С уважением,

 
 
 
 Re: [C++]неориентированный граф
Сообщение15.05.2012, 01:11 
код: [ скачать ] [ спрятать ]
Используется синтаксис C++
 #include <iostream>
 #include <fstream>
 #include <string>

 using namespace std;

 string str(int d)
 {
 int n = 10;
 string s = "";
 while(d != 0)
 {
 s = char(((d%n)/(n/10))+48) + s;
 d = d - (d%n);
 n *= 10;
 }
 return s;
 }



 struct link
 {
 int data;
 link* next;
 };


 class linklist
 {
 private:
 link* first;
 public:
 bool e;

 linklist ( )
 {
 first = NULL;
 e = false;
 }

 void additem ( int d );
 void linklist::display ( );
 bool exist(int x);
 void makenull();


 };

 void linklist::additem ( int d ) // добавление элемента
 {
 link* newlink = new link; // выделяем память
 newlink->data = d; // запоминаем данные
 newlink->next = first; // запоминаем значение first
 first = newlink; // first теперь указывает на новый элемент
 }

 void linklist::display ( )
 {
 link* current = first; // начинаем с первого элемента
 while( current ) // пока есть данные
 {
 cout << current->data << endl; // печатаем данные
 current = current->next; // двигаемся к следующему элементу
 }
 }

 bool exist(int x)
 {
 link* current = first;
 if (!current) return 0;
 while( current )
 {
 if (current->data == x)
 {
 return 1;
 break;
 }
 current = current->next;
 }

 if (current == NULL)
 return 0;
 }

 void makenull()
 {
 link* current = first;
 link* deleted = new link;
 while(!(current))
 {
 deleted = current;
 current = current->next;
 delete deleted;
 }
 first = NULL ;
 cout<<"Linklist is free";
 }


 class Graph
 {
 private:

 linklist adj[1000];

 public:

 Graph ( )
 { }

 void addedge (int x,int y);
 void addvertex (int x);
 void deledge (int x,int y);
 void delvertex (int x);
 void load();
 void save();



 void q(int n);
 void d(int x);
 void IsFull(G);
 void D(v,1);

 };


 void Graph::addedge(int x,int y)
 {
 if ((adj[x].e == true) && (adj[y].e == true) && (adj[x].exist(y) == false) && (adj[y].exist(x)==false) && (x!=y))
 {
 adj[x].additem(y);
 adj[y].additem(x);
 }
 else cout<<"Error"<<endl;
 }

 void Graph::addvertex(int x)
 {

 if (adj[x].e==false)
 adj[x].e=true;
 else
 cout<<"Vertise is !!!"<<endl;
 }

 void Graph::deledge (int x,int y)
 {
 if ((adj[x].e == true) && (adj[y].e == true) && (adj[x].exist(y) == true) && (adj[y].exist(x) == true) && (x!=y))
 {
 adj[x].delitem(y);
 adj[y].delitem(x);
 }
 else cout<<"Error"<<endl;
 }

 void Graph::delvertex(int x)
 {
 if (adj[x].e == true)
 {
 adj[x].e = false;
 adj[x].makenull();

 for (int i = 1; i < 1000; i++)
 {
 if (adj[i].exist(x) == 1)
 adj[i].delitem(x);
 }
 }
 else
 cout<<"Vertise is not !!!"<<endl;
 }

 void Graph::save()
 {
 string s = "";
 for(int i = 1;i <= 1000; i++)
 {
 if(adj[i].e == true)
 {
 /*cout<<"save"<<endl;
 s = s + str(i) + " - ";
 out.write(s.c_str(),s.size());*/

 adj[i].save(i);
 }
 //out.close();
 }
 }

 void Graph::display()
 {
 for (int i = 1; i < 1000; i++)
 {
 if (adj[i].e == true)
 {
 cout<<i<<" - ";
 adj[i].display();
 cout<<endl;
 }
 }
 }

 void Graph::q(int n)
 {
 int d = 0;
 for (int i = 1; i <= n; i++)
 {
 if (adj[i].e == true)
 d = d + adj[i].Putnumberver();
 }
 cout<<"There are "<<(d/2)<<" edges in the Graph"<<endl;
 }

 void Graph::d(int x)
 {
 cout<<"The degree of vertex "<<x<<" is "<<adj[x].Putnumberver()<<endl;
насколько я знаю,эта часть программы составленна верно,только надо дореализовывать методы  
 void IsFull(G);
 void D(v,1);(описание которых представленно выше)
дальше я прошу помощи в разборке кода этих методов и основной части...

 }


 i  Lady000, если Вы еще раз запостите такую простыню кода без использования тега syntax, тема уедет в Карантин.
/Toucan

 
 
 
 Re: [C++]неориентированный граф
Сообщение15.05.2012, 16:44 
hurtsy в сообщении #570758 писал(а):
Lady000 в сообщении #570749 писал(а):
какие синтаксические ошибки?


Вот часть сообщений транслятора, которые обязательно нужно учесть в вашей программе.
  1. [C++ Error] Unit1.cpp(75): E2451 Undefined symbol 'first'
  2. [C++ Error] Unit1.cpp(157): E2316 'delitem' is not a member of 'linklist'
  3. [C++ Error] Unit1.cpp(190): E2316 'save' is not a member of 'linklist'
  4. [C++ Error] Unit1.cpp(197): E2316 'Graph::display()' is not a member of 'Graph'
  5. [C++ Error] Unit1.cpp(215): E2316 'Putnumberver' is not a member of 'linklist'

Сообщение 1 относится к
Код:
void makenull()
{
link* current = first;
link* deleted = new link;

должно быть
Код:
void linklist::makenull()
{
link* current = first;
link* deleted = new link;

Транслятор определил эту ошибку по переменной first, а проблемма в описании функции.
Понять транслятор не очень легко но интересно.
После того как вам удастся исправить все ошибки трансляции прийдется исправлять ошибки на которые укажет linker. А после этого можно будет заниматься отладкой. С уважением,

 
 
 
 Re: [C++]неориентированный граф
Сообщение16.05.2012, 22:05 
код: [ скачать ] [ спрятать ]
Используется синтаксис C++
  1.  #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. string str(int d)
  8. {
  9.         int n = 10;
  10.         string s = "";
  11.         while(d != 0)
  12.         {
  13.                 s = char(((d%n)/(n/10))+48) + s;
  14.                 d = d - (d%n);
  15.                 n *= 10;
  16.         }
  17.         return s;
  18. }
  19.  
  20.  
  21.  
  22. struct link
  23. {
  24.         int data;
  25.         link* next;
  26. };
  27.  
  28.  
  29. class linklist
  30. {
  31.         private:
  32.                 link* first;
  33.         public:
  34.         bool e;
  35.  
  36.         linklist ( )
  37.         {
  38.                 first = NULL;
  39.                 e = false;
  40.         }
  41.  
  42. void additem ( int d );//добавление элемента
  43. void display ( );//вывод списка
  44. bool exist(int x);//проверка вхождения элемента в список
  45. void makenull();//опустошение списка
  46. void delitem(int d) ;
  47. int Putnumberver( );
  48. };
  49.  
  50.  
  51.  
  52. int linklist::Putnumberver()
  53. {
  54.         link* current = new link;
  55.         current = first;
  56.         int d = 0;
  57.         while(current)
  58.         {
  59.                 d += 1;
  60.                 current = current ->next;
  61.         }
  62.         return d;
  63. }
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.     void linklist::delitem(int d)
  71.         {
  72.      link* current = new link;
  73.      link* prev = new link;
  74.          int t = 0;
  75.  
  76.      current = first;
  77.      prev = current;
  78.  
  79.          
  80.      while(current)
  81.      {
  82.                  current->data = t;
  83.                         if(t == d)
  84.                         {
  85.                                         prev -> next = current -> next;
  86.                     delete[]current;
  87.                     current = prev -> next;
  88.                         }
  89.                         else
  90.                         {
  91.                        prev = current;
  92.                        current = current->next;
  93.                         }
  94.      }
  95.        
  96.         }
  97.  
  98.  
  99.  
  100.  
  101.  
  102.  
  103.  
  104. void linklist::additem ( int d ) // добавление элемента
  105. {
  106.   link* newlink = new link;      // выделяем память
  107.   newlink->data = d;             // запоминаем данные
  108.   newlink->next = first;         // запоминаем значение first
  109.   first = newlink;               // first теперь указывает на новый элемент
  110. }
  111.  
  112. void linklist::display ( )
  113. {
  114.   link* current = first;           // начинаем с первого элемента
  115.   while( current )                 // пока есть данные
  116.   {
  117.     cout << current->data << endl; // печатаем данные
  118.     current = current->next;       // двигаемся к следующему элементу
  119.   }
  120. }
  121.  
  122.     bool linklist:: exist(int x)
  123.      {
  124.       link* current = first;          
  125.       if (!current) return 0;
  126.       while( current )                
  127.       {
  128.              if (current->data == x)
  129.              {
  130.               return 1;
  131.               break;
  132.              }  
  133.              current = current->next;    
  134.       }
  135.            
  136.       if (current == NULL)
  137.       return 0;
  138.   }
  139.  
  140.     void linklist::makenull()
  141.     {
  142.      link* current = first;          
  143.      link* deleted = new link;
  144.            while(!(current))                
  145.            {  
  146.                deleted = current;          
  147.                current = current->next;      
  148.                delete deleted;              
  149.            }
  150.            first = NULL  ;
  151.            cout<<"Linklist is free";
  152.      }
  153.    
  154.  
  155. class Graph
  156.  
  157.  
  158.  
  159. {
  160.   private:
  161.  
  162.    linklist adj[1000];  
  163.  
  164.   public:
  165.  
  166.     Graph ( )      
  167.       {  }  
  168.  
  169.     void addedge (int x,int y);
  170.     void addvertex (int x);
  171.     void deledge (int x,int y);
  172.     void delvertex (int x);
  173.     void p(int n);
  174.     void q(int n);
  175.     void d(int x);
  176.     void display ();
  177.     void saves();
  178.     void Load();
  179.     void D1(int x);
  180.     void IsF(int n, int x, int y);
  181. };
  182.  
  183.         void Graph::Load()
  184.         {
  185.                 char str[50];
  186.                
  187.  
  188.                 int j = 0,i = 0,z = 0;
  189.                 ifstream file("Graph.txt");
  190.                
  191.                 while(file)
  192.                 {
  193.                         file.getline(str,50);
  194.                         i = static_cast<int>(str[0] - 48);
  195.                        
  196.                                 if(i != -48)
  197.                                 addvertex(i);
  198.                        
  199.                 }
  200.                 file.close();
  201.  
  202.                 ifstream file1("Graph.txt");
  203.                 while(file1)
  204.                 {
  205.                         file1.getline(str,50);
  206.                         z = static_cast<int>(str[0] - 48);
  207.                        
  208.                         for(int k = 2; k < 50; k++)
  209.                         {
  210.                                 i = static_cast<int>(str[k] - 48);
  211.                                 addedge(z,i);
  212.                         }
  213.                 }
  214.                 file.close();
  215.         }
  216.  
  217.  
  218.         void Graph::saves()
  219.         {
  220.                  ofstream file1;
  221.  
  222.                 for(int i = 1;i <= 1000; i++)
  223.                 {
  224.                           if(adj[i].e == true)
  225.                                  {             
  226.  
  227.                                          file1.open("Граф.txt",std::ios_base::app);
  228.                                          file1<<"Вершина "<<i<<" - ";
  229.                                          file1.close();
  230.  
  231.                                          file1.open("Graph.txt",std::ios_base::app);
  232.                                          file1<<i<<" ";
  233.                                          file1.close();
  234.  
  235.                                          adj[i].save();
  236.                                  }
  237.          }
  238.         }
  239.  
  240.         void Graph::addvertex(int x)
  241.         {
  242.  
  243.                  if (adj[x].e==false)
  244.                         adj[x].e=true;
  245.                  else
  246.                          cout<<"Такая вершина уже существует"<<endl;
  247.         }
  248.  
  249.  
  250.  
  251.         void Graph::addedge(int x,int y)
  252.         {
  253.                 if ((adj[x].e == true) && (adj[y].e == true) && (adj[x].exist(y) == false) && (adj[y].exist(x)==false) && (x!=y))
  254.                 {
  255.                         adj[x].additem(y);
  256.                         adj[y].additem(x);
  257.                 }
  258.                 /*else
  259.                         cout<<"Ошибка,одна или обе вершины отсутствуют или между ними уже сть ребро"<<endl;*/
  260.         }
  261.  
  262.  
  263.         void Graph::display()
  264.         {
  265.                 for (int i = 1; i < 1000; i++)
  266.                 {
  267.                         if (adj[i].e == true)
  268.                         {
  269.                         cout<<"Вершина с номером "<<i<<" - смежные с ней вершины: ";
  270.                         adj[i].display();
  271.                         cout<<endl;
  272.                         }
  273.                 }
  274.         }
  275.  
  276.         void Graph::deledge (int x,int y)
  277.         {
  278.                  if ((adj[x].e == true) && (adj[y].e == true) && (adj[x].exist(y) == true) && (adj[y].exist(x) == true) && (x!=y))
  279.                 {
  280.                         adj[x].delitem(y);
  281.                         adj[y].delitem(x);
  282.                 }
  283.                 else
  284.                         cout<<"Ошибка"<<endl;
  285.         }
  286.  
  287.  
  288.         void Graph::delvertex(int x)
  289.         {
  290.    
  291.                 if (adj[x].e == true)
  292.                 {
  293.                         adj[x].e = false;
  294.                         adj[x].makenull();
  295.        
  296.                         for (int i = 1; i < 1000; i++)
  297.                         {
  298.                                 if (adj[i].exist(x) == 1)
  299.                                         adj[i].delitem(x);
  300.                         }
  301.                 }
  302.                 else
  303.                         cout<<"Такая вершина отсутсвует"<<endl;
  304.         }
  305.  
  306.         void Graph::p(int n)
  307.         {
  308.                 int d = 0;
  309.                 for (int i = 1; i <= n; i++)
  310.                 {
  311.                         if (adj[i].e == true)
  312.                                 d++;
  313.                 }
  314.        
  315.                 cout<<"В графе существует "<<d<<" вершин"<<endl;  
  316.         }
  317.  
  318.         void Graph::q(int n)
  319.         {
  320.                 int d = 0;
  321.                 for (int i = 1; i <= n; i++)
  322.                 {
  323.                         if (adj[i].e == true)
  324.                          d = d + adj[i].Putnumberver();
  325.                 }
  326.        
  327.                 cout<<"В графе существует "<<(d/2)<<" ребер"<<endl;    
  328.         }
  329.  
  330.         void Graph::d(int x)
  331.         {
  332.                  cout<<"Степень вершины "<<x<<" равна "<<adj[x].Putnumberver()<<endl;
  333.  
  334.         }
  335.        
  336.  
  337.         void Graph::D1( int x)
  338.             {
  339.                if (adj[x].e==true)
  340.                   {
  341.                     adj[x].display;
  342.                   }
  343.                   else
  344.                    cout<<"error";
  345.  
  346.  
  347.             }
  348.  
  349.         void Graph::IsF(int n, int x, int y)
  350.         {
  351.                 for (int x = 1; x <=n ;x++)
  352.                 {
  353.                         for (int y = 1; x <=n ;x++)
  354.                         {
  355.                                 if ((adj[x].e == true) && (adj[y].e == true) && (adj[x].exist(y) == true) && (adj[y].exist(x) == true) && (x!=y))
  356.                                         cout<<"Полнота есть"<<endl;
  357.                                 else
  358.                                         cout<<"Полноты нет"<<endl;
  359.                         }
  360.                 }
  361.  
  362.  
  363.         }
  364.  
  365.  
  366.  
  367. int _tmain(int argc, _TCHAR* argv[])
  368. {
  369.         setlocale(LC_ALL, "Russian");
  370.  
  371.         Graph G;
  372.         int s = 0,n = 0,x = 0,y = 0,v = 0;
  373.    
  374.    
  375.      while(true)
  376.          {
  377.      
  378.        cout<<"Что вы хотите сделать с графом?"<<endl
  379.           <<"1 - Добавить вершину"<<endl
  380.           <<"2 - Добавить ребро"<<endl
  381.           <<"3 - Удалить вершину"<<endl
  382.           <<"4 - Удалить ребро"<<endl
  383.           <<"5 - Посчитать количество ребер"<<endl
  384.           <<"6 - Посчитать количество вершин"<<endl
  385.           <<"7 - Вывести степень вершины"<<endl
  386.           <<"8 - Вывести граф на экран"<<endl
  387.           <<"9 - Сохранить граф"<<endl
  388.           <<"10 - Загрузить граф"<<endl
  389.           <<"11 - Выйти"<<endl
  390.                   <<"12 - Возвращает список вершин, удалённых на расстояние n от вершины v"<<endl
  391.                   <<"13 - ПРоверка графа на полноту"<<endl;
  392.       cin>>v;
  393.          
  394.      
  395.  
  396.       if(v == 1)
  397.       {
  398.         cout<<"Введите номер новой вершины"<<endl;
  399.         cin>>x;
  400.         G.addvertex(x);
  401.         n++;
  402.       }
  403.      
  404.       if(v == 2)
  405.       {
  406.         cout<<"Введите номера двух соединяемых вершин "<<endl;
  407.         cin>>x>>y;
  408.         G.addedge(x,y);
  409.       }
  410.  
  411.       if(v == 3)
  412.       {
  413.         cout<<"Введите номер удаляемой вершины"<<endl;
  414.         cin>>x;
  415.         G.delvertex(x);
  416.       }
  417.      
  418.       if(v == 4)
  419.       {
  420.         cout<<"Введите номера двух вершин,между которыми вы хотите удалить ребро"<<endl;
  421.         cin>>x>>y;
  422.         G.deledge(x,y);
  423.       }
  424.  
  425.       if(v == 5)
  426.       {
  427.         G.q(n);
  428.       }
  429.      
  430.       if(v == 6)
  431.       {
  432.         G.p(n);
  433.       }
  434.  
  435.       if(v == 7)
  436.       {
  437.         cout<<"Введите номер вершины,степень которой вы хотите вывести "<<endl;
  438.         cin>>x;
  439.         G.d(x);
  440.       }
  441.      
  442.       if(v == 8)
  443.        G.display();
  444.        
  445.       if(v == 9)
  446.       {
  447.         G.saves();
  448.       }
  449.        
  450.       if(v == 10)
  451.       {
  452.                  G.Load();
  453.       }
  454.  
  455.       if(v == 11)
  456.         break;
  457.  
  458.           if(v == 12)
  459.           {
  460.              G.D1(x);
  461.           }
  462.  
  463.           if(v == 13)
  464.           {
  465.                  G.IsF(n,x,y);
  466.           }
  467.    }
  468.    
  469.    
  470.      
  471.    
  472.     system("pause");
  473.  
  474.         return 0;
  475. }
  476.  
  477.  
  478.  

всё исправленно,ошибки остались 2 или 3,клторые не знаю как исправить,во первых прога вообще не запускается:(компилятор отказывается работать(

 
 
 
 Re: [C++]неориентированный граф
Сообщение16.05.2012, 23:09 
код: [ скачать ] [ спрятать ]
Используется синтаксис C++
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <conio.h>
  5.  
  6. using namespace std;
  7.  
  8. string str(int d)
  9. {
  10.         int n = 10;
  11.         string s = "";
  12.         while(d != 0)
  13.         {
  14.                 s = char(((d%n)/(n/10))+48) + s;
  15.                 d = d - (d%n);
  16.                 n *= 10;
  17.         }
  18.         return s;
  19. }
  20.  
  21.  
  22.  
  23. struct link
  24. {
  25.         int data;
  26.         link* next;
  27. };
  28.  
  29.  
  30. class linklist
  31. {
  32.         private:
  33.                 link* first;
  34.         public:
  35.         bool e;
  36.  
  37.         linklist ( )
  38.         {
  39.                 first = NULL;
  40.                 e = false;
  41.         }
  42.  
  43. void additem ( int d );//добавление элемента
  44. void display ( );//вывод списка
  45. bool exist(int x);//проверка вхождения элемента в список
  46. void makenull();//опустошение списка
  47. void delitem(int d) ;
  48. int Putnumberver( );
  49. };
  50.  
  51.  
  52.  
  53. int linklist::Putnumberver()
  54. {
  55.         link* current = new link;
  56.         current = first;
  57.         int d = 0;
  58.         while(current)
  59.         {
  60.                 d += 1;
  61.                 current = current ->next;
  62.         }
  63.         return d;
  64. }
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71.     void linklist::delitem(int d)
  72.         {
  73.      link* current = new link;
  74.      link* prev = new link;
  75.          int t = 0;
  76.  
  77.      current = first;
  78.      prev = current;
  79.  
  80.          
  81.      while(current)
  82.      {
  83.                  current->data = t;
  84.                         if(t == d)
  85.                         {
  86.                                         prev -> next = current -> next;
  87.                     delete[]current;
  88.                     current = prev -> next;
  89.                         }
  90.                         else
  91.                         {
  92.                        prev = current;
  93.                        current = current->next;
  94.                         }
  95.      }
  96.        
  97.         }
  98.  
  99.  
  100.  
  101.  
  102.  
  103.  
  104.  
  105. void linklist::additem ( int d ) // добавление элемента
  106. {
  107.   link* newlink = new link;      // выделяем память
  108.   newlink->data = d;             // запоминаем данные
  109.   newlink->next = first;         // запоминаем значение first
  110.   first = newlink;               // first теперь указывает на новый элемент
  111. }
  112.  
  113. void linklist::display ( )
  114. {
  115.   link* current = first;           // начинаем с первого элемента
  116.   while( current )                 // пока есть данные
  117.   {
  118.     cout << current->data << endl; // печатаем данные
  119.     current = current->next;       // двигаемся к следующему элементу
  120.   }
  121. }
  122.  
  123.     bool linklist:: exist(int x)
  124.      {
  125.       link* current = first;          
  126.       if (!current) return 0;
  127.       while( current )                
  128.       {
  129.              if (current->data == x)
  130.              {
  131.               return 1;
  132.               break;
  133.              }  
  134.              current = current->next;    
  135.       }
  136.            
  137.       if (current == NULL)
  138.       return 0;
  139.   }
  140.  
  141.     void linklist::makenull()
  142.     {
  143.      link* current = first;          
  144.      link* deleted = new link;
  145.            while(!(current))                
  146.            {  
  147.                deleted = current;          
  148.                current = current->next;      
  149.                delete deleted;              
  150.            }
  151.            first = NULL  ;
  152.            cout<<"Linklist is free";
  153.      }
  154.    
  155.  
  156. class Graph
  157.  
  158.  
  159.  
  160. {
  161.   private:
  162.  
  163.    linklist adj[1000];  
  164.  
  165.   public:
  166.  
  167.     Graph ( )      
  168.       {  }  
  169.  
  170.     void addedge (int x,int y);
  171.     void addvertex (int x);
  172.     void deledge (int x,int y);
  173.     void delvertex (int x);
  174.     void display ( );
  175.     void p(int n);
  176.     void q(int n);
  177.     void d(int x);
  178.     void display ();
  179.     void saves();
  180.     void Load();
  181.     void D1(int x);
  182.     void IsF(int n, int x, int y);
  183. };
  184.  
  185.         void Graph::Load()
  186.         {
  187.                 char str[50];
  188.                
  189.  
  190.                 int j = 0,i = 0,z = 0;
  191.                 ifstream file("Graph.txt");
  192.                
  193.                 while(file)
  194.                 {
  195.                         file.getline(str,50);
  196.                         i = static_cast<int>(str[0] - 48);
  197.                        
  198.                                 if(i != -48)
  199.                                 addvertex(i);
  200.                        
  201.                 }
  202.                 file.close();
  203.  
  204.                 ifstream file1("Graph.txt");
  205.                 while(file1)
  206.                 {
  207.                         file1.getline(str,50);
  208.                         z = static_cast<int>(str[0] - 48);
  209.                        
  210.                         for(int k = 2; k < 50; k++)
  211.                         {
  212.                                 i = static_cast<int>(str[k] - 48);
  213.                                 addedge(z,i);
  214.                         }
  215.                 }
  216.                 file.close();
  217.         }
  218.  
  219.  
  220.         /*void Graph::saves()
  221.         {
  222.                  ofstream file1;
  223.  
  224.                 for(int i = 1;i <= 1000; i++)
  225.                 {
  226.                           if(adj[i].e == true)
  227.                                  {             
  228.  
  229.                                          file1.open("Граф.txt",std::ios_base::app);
  230.                                          file1<<"Вершина "<<i<<" - ";
  231.                                          file1.close();
  232.  
  233.                                          file1.open("Graph.txt",std::ios_base::app);
  234.                                          file1<<i<<" ";
  235.                                          file1.close();
  236.  
  237.                                          adj[i].save();
  238.                                  }
  239.          }
  240.         }*/
  241.  
  242.         void Graph::addvertex(int x)
  243.         {
  244.  
  245.                  if (adj[x].e==false)
  246.                         adj[x].e=true;
  247.                  else
  248.                          cout<<"Такая вершина уже существует"<<endl;
  249.         }
  250.  
  251.  
  252.  
  253.         void Graph::addedge(int x,int y)
  254.         {
  255.                 if ((adj[x].e == true) && (adj[y].e == true) && (adj[x].exist(y) == false) && (adj[y].exist(x)==false) && (x!=y))
  256.                 {
  257.                         adj[x].additem(y);
  258.                         adj[y].additem(x);
  259.                 }
  260.                 /*else
  261.                         cout<<"Ошибка,одна или обе вершины отсутствуют или между ними уже сть ребро"<<endl;*/
  262.         }
  263.  
  264.  
  265.         void Graph::display()
  266.         {
  267.                 for (int i = 1; i < 1000; i++)
  268.                 {
  269.                         if (adj[i].e == true)
  270.                         {
  271.                         cout<<"Вершина с номером "<<i<<" - смежные с ней вершины: ";
  272.                         adj[i].display();
  273.                         cout<<endl;
  274.                         }
  275.                 }
  276.         }
  277.  
  278.         void Graph::deledge (int x,int y)
  279.         {
  280.                  if ((adj[x].e == true) && (adj[y].e == true) && (adj[x].exist(y) == true) && (adj[y].exist(x) == true) && (x!=y))
  281.                 {
  282.                         adj[x].delitem(y);
  283.                         adj[y].delitem(x);
  284.                 }
  285.                 else
  286.                         cout<<"Ошибка"<<endl;
  287.         }
  288.  
  289.  
  290.         void Graph::delvertex(int x)
  291.         {
  292.    
  293.                 if (adj[x].e == true)
  294.                 {
  295.                         adj[x].e = false;
  296.                         adj[x].makenull();
  297.        
  298.                         for (int i = 1; i < 1000; i++)
  299.                         {
  300.                                 if (adj[i].exist(x) == 1)
  301.                                         adj[i].delitem(x);
  302.                         }
  303.                 }
  304.                 else
  305.                         cout<<"Такая вершина отсутсвует"<<endl;
  306.         }
  307.  
  308.         void Graph::p(int n)
  309.         {
  310.                 int d = 0;
  311.                 for (int i = 1; i <= n; i++)
  312.                 {
  313.                         if (adj[i].e == true)
  314.                                 d++;
  315.                 }
  316.        
  317.                 cout<<"В графе существует "<<d<<" вершин"<<endl;  
  318.         }
  319.  
  320.         void Graph::q(int n)
  321.         {
  322.                 int d = 0;
  323.                 for (int i = 1; i <= n; i++)
  324.                 {
  325.                         if (adj[i].e == true)
  326.                          d = d + adj[i].Putnumberver();
  327.                 }
  328.        
  329.                 cout<<"В графе существует "<<(d/2)<<" ребер"<<endl;    
  330.         }
  331.  
  332.         void Graph::d(int x)
  333.         {
  334.                  cout<<"Степень вершины "<<x<<" равна "<<adj[x].Putnumberver()<<endl;
  335.  
  336.         }
  337.        
  338.  
  339.         void Graph::D1( int x)
  340.             {
  341.                if (adj[x].e==true)
  342.                   {
  343.                     adj[x].display;
  344.                   }
  345.                   else
  346.                    cout<<"error";
  347.  
  348.  
  349.             }
  350.  
  351.         void Graph::IsF(int n, int x, int y)
  352.         {
  353.                 for (int x = 1; x <=n ;x++)
  354.                 {
  355.                         for (int y = 1; x <=n ;x++)
  356.                         {
  357.                                 if ((adj[x].e == true) && (adj[y].e == true) && (adj[x].exist(y) == true) && (adj[y].exist(x) == true) && (x!=y))
  358.                                         cout<<"Полнота есть"<<endl;
  359.                                 else
  360.                                         cout<<"Полноты нет"<<endl;
  361.                         }
  362.                 }
  363.  
  364.  
  365.         }
  366.  
  367.  
  368.  
  369. int _tmain(int argc, _TCHAR* argv[])
  370. {
  371.         setlocale(LC_ALL, "Russian");
  372.  
  373.         Graph G;
  374.         int s = 0,n = 0,x = 0,y = 0,v = 0;
  375. char sw='y';
  376.   Graph G;       // создаем переменную-список
  377.   cout<<"enter number of vertexs"<<endl;
  378.   cin>>n;
  379.  
  380.  
  381.  
  382.  
  383.   while (n>0)
  384.   {
  385.      cout<<"enter marker of new vertex - ";
  386.      cin>>x;
  387.      G.addvertex(x) ; // добавляем туда несколько чисел
  388.      n--;
  389.   }
  390.  
  391.  
  392.   while (sw!='n')
  393.   {
  394.      cout<<"enter vertexs which you would like to connect - (x,y)"<<endl;
  395.      cin>>x;
  396.      cin>>y;
  397.      G.addedge(x,y) ; // добавляем туда несколько чисел
  398.     cout<<"do you want to enter more vertexs (y/n)? "<<endl;
  399.     sw=getch();
  400.   }
  401.   G.display ( );    // показываем список
  402.  
  403.  
  404.    
  405.    
  406.      while(true)
  407.          {
  408.      
  409.        cout<<"Что вы хотите сделать с графом?"<<endl
  410.           <<"1 - Добавить вершину"<<endl
  411.           <<"2 - Добавить ребро"<<endl
  412.           <<"3 - Удалить вершину"<<endl
  413.           <<"4 - Удалить ребро"<<endl
  414.           <<"5 - Посчитать количество ребер"<<endl
  415.           <<"6 - Посчитать количество вершин"<<endl
  416.           <<"7 - Вывести степень вершины"<<endl
  417.           <<"8 - Вывести граф на экран"<<endl
  418.           <<"9 - Сохранить граф"<<endl
  419.           <<"10 - Загрузить граф"<<endl
  420.           <<"11 - Выйти"<<endl
  421.                   <<"12 - Возвращает список вершин, удалённых на расстояние n от вершины v"<<endl
  422.                   <<"13 - ПРоверка графа на полноту"<<endl;
  423.       cin>>v;
  424.          
  425.      
  426.  
  427.       if(v == 1)
  428.       {
  429.         cout<<"Введите номер новой вершины"<<endl;
  430.         cin>>x;
  431.         G.addvertex(x);
  432.         n++;
  433.       }
  434.      
  435.       if(v == 2)
  436.       {
  437.         cout<<"Введите номера двух соединяемых вершин "<<endl;
  438.         cin>>x>>y;
  439.         G.addedge(x,y);
  440.       }
  441.  
  442.       if(v == 3)
  443.       {
  444.         cout<<"Введите номер удаляемой вершины"<<endl;
  445.         cin>>x;
  446.         G.delvertex(x);
  447.       }
  448.      
  449.       if(v == 4)
  450.       {
  451.         cout<<"Введите номера двух вершин,между которыми вы хотите удалить ребро"<<endl;
  452.         cin>>x>>y;
  453.         G.deledge(x,y);
  454.       }
  455.  
  456.       if(v == 5)
  457.       {
  458.         G.q(n);
  459.       }
  460.      
  461.       if(v == 6)
  462.       {
  463.         G.p(n);
  464.       }
  465.  
  466.       if(v == 7)
  467.       {
  468.         cout<<"Введите номер вершины,степень которой вы хотите вывести "<<endl;
  469.         cin>>x;
  470.         G.d(x);
  471.       }
  472.      
  473.       if(v == 8)
  474.        G.display();
  475.        
  476.       if(v == 9)
  477.       {
  478.         G.saves();
  479.       }
  480.        
  481.       if(v == 10)
  482.       {
  483.                  G.Load();
  484.       }
  485.  
  486.       if(v == 11)
  487.         break;
  488.  
  489.           if(v == 12)
  490.           {
  491.              G.D1(x);
  492.           }
  493.  
  494.           if(v == 13)
  495.           {
  496.                  G.IsF(n,x,y);
  497.           }
  498.    }
  499.  
  500.    
  501.      
  502.    
  503.     system("pause");
  504.  
  505.         return 0;
  506. }
  507.  
  508.  
  509.  


Ещё исправила кое что ,но програ не запускается и ф-я D(v,1)не реализуется(((

 
 
 
 Re: [C++]неориентированный граф
Сообщение16.05.2012, 23:23 
Аватара пользователя
 i  Lady000, тег syntax для вывода программы на C++ с нумерацией строк записывается так:
Код:
[syntax lang=cpp lines=n]
...
[/syntax]
Поправил.

 
 
 
 Re: [C++]неориентированный граф
Сообщение17.05.2012, 00:28 
Lady000 в сообщении #572084 писал(а):
Используется синтаксис C++
// 1, 2
if (v == 3)
{
    // ...
}
if (v == 4)
{
    // ...
}
if (v == 5)
{
    // ...
}
// 6, 7, 8, 9, 10, 11, 12, 13
Видели оператор switch? :?

Перепишите оставшиеся ошибки, пожалуйста, в тему.

 
 
 
 Re: [C++]неориентированный граф
Сообщение17.05.2012, 01:20 
arseniiv в сообщении #572120 писал(а):
Видели оператор switch?


а он тут зачем?я вас не поняла..а в синтаксе то где проблема?ведь то же самое, что и у вас написано

 
 
 
 Re: [C++]неориентированный граф
Сообщение17.05.2012, 14:14 
Lady000
arseniiv в сообщении #572120 писал(а):
Видели оператор switch? :?

Перепишите оставшиеся ошибки, пожалуйста, в тему.


И тем не менее, "Лёд тронулся".

Я записал протокол исправлений
Цитата:
[C++ Error] Unit1.cpp(178): E2238 Multiple declaration for 'Graph::display()'
[C++ Error] Unit1.cpp(174): E2344 Earlier declaration of 'Graph::display()'
оператор на 178 закоментировать
Транслятор выдает новое
[C++ Error] Unit1.cpp(343): E2235 Member function must be called or its address taken
[C++ Error] Unit1.cpp(376): E2238 Multiple declaration for 'G'
[C++ Error] Unit1.cpp(373): E2344 Earlier declaration of 'G'
вместо adj[x].display; adj[x].display();
376 закоментировать
Транлятор дал добро, но появилась ошибка линкера
[Linker Error] Unresolved external '__stdcall Graph::saves()' referenced from
C:\PROGRAM FILES\BORLAND\CBUILDER6\PROJECTS\DXDY\UNIT1.OBJ
220-240 снять комментарий
Опять транслятор недоволен

[C++ Error] Unit1.cpp(237): E2316 'save' is not a member of 'linklist'

Оказывается в классе linklist нет saves()

нужно добавить void saves(void);
и описание

void linklist::saves(void){
//это заглушка
}
Заглушка это временное, решение вопроса за вами.
И наконец, как говорил Матроскин заработало :o
Вот теперь мы видим консоль и начинается отладка.

Теперь можно, по совету ЗУ arseniiv, указанные им операторы заменить(если пожелаете, а опыт программирования говорит, что switch работает быстрее) на switch.
С уважением

 
 
 
 Re: [C++]неориентированный граф
Сообщение17.05.2012, 17:08 
Лучше ничего не менять, пока не исправлены ошибки компиляции. Но всё же странно.

-- Чт май 17, 2012 20:14:58 --

hurtsy в сообщении #572352 писал(а):
switch работает быстрее
Если это и так в C++, дело не в этом.

 
 
 
 Re: [C++]неориентированный граф
Сообщение17.05.2012, 17:57 
arseniiv в сообщении #572457 писал(а):
Если это и так в C++, дело не в этом.

В реализации ТС в любом случае производится 13 проверок иф-условий. Можно конечно использовать else. Но ещё нужно учитывать оптимизаторскую деятельность компилятора.

В тех правках, которые я предложил, ошибки компилятора кончились. А что вам кажется странным? С уважением,

 
 
 
 Re: [C++]неориентированный граф
Сообщение17.05.2012, 18:04 
Если подумать, ничего.

hurtsy в сообщении #572477 писал(а):
В тех правках, которые я предложил, ошибки компилятора кончились.
Вы уверены, что это правильный ход? ТС уже давно не появляется. Интересно, почему?

 
 
 [ Сообщений: 18 ]  На страницу 1, 2  След.


Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group