
21.05.2008, 12:39
|
|
Новичок
Регистрация: 08.02.2008
Сообщений: 12
С нами:
9607368
Репутация:
2
|
|
Помогите плз
Разреженный массив на основе статического массива указателей
Тип элементов раз-реженного массива данных - структура с полями: регистрационный номер, ФИО, ад-рес, ИНН.
Данные. Размер массива, массив указателей на данные.
Операции. Конструктор с параметром, инициализирующий размер массива и запол-няющий все элементы массива указателей значением 0. Получение значения элемента по его индексу. Подсчет количества непус-тых элементов в массиве данных. Вывод элементов массива.
вот лаба :
Код:
#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <vcl.h>
#pragma argsused
struct info
{
int RegCode;
char FIO[25];
char Address[255];
int INN;
};
class array
{
private:
int size;
info** a;
int counter;
void SetArray( int );
public:
array( int );
~array();
void Input();
void Output();
void OutputByIndex();
void GetSize();
};
array::array(int size)
{
SetArray(size);
}
array::~array()
{
for( int i = 0; i < counter; i++ )
{
delete a[i];
}
delete []a;
}
void array::SetArray(int siz)
{
a = new info*[siz];
for(int i = 0; i < siz; i++)
{
a[i] = 0;
}
size = siz;
counter = 0;
}
void array::Input()
{
if( counter != size )
{
a[ counter ] = new info;
cout << "Input registration code: ";
cin >> a[ counter ]-> RegCode;
cout << "Input FIO: ";
cin.get();
cin.getline(a[ counter ]->FIO, 25);
cout << "Input address: ";
cin.getline(a[ counter ]->Address,255);
cout << "Input INN: ";
cin >> a[ counter ]->INN;
counter++;
}
else
{
cout << "Error. Array is full";
}
}
void array::Output()
{
if( counter )
{
for( int i = counter - 1; i >= 0; i--)
{
cout << "Registration code: " << a[ i ]->RegCode << "\n";
cout << "FIO: " << a[ i ]->FIO << "\n";
cout << "Address: " << a[ i ]->Address << "\n";
cout << "INN: " << a[ i ]->INN << "\n";
cout << "\r\n";
}
}
else
{
cout << "Error. Array is empty";
}
}
void array::OutputByIndex()
{
int ind;
cout << "Input index: ";
cin >> ind;
if( counter )
{
if( ind >= counter )
cout << "Error. Index out of range";
else
{
cout << "Registration code: " << a[ ind ]->RegCode << "\n";
cout << "FIO: " << a[ ind ]->FIO << "\n";
cout << "Address: " << a[ ind ]->Address << "\n";
cout << "INN: " << a[ ind ]->INN << "\n";
cout << "\r\n";
}
}
else
cout << "Array is empty\n";
}
void array::GetSize()
{
cout << counter << "\n";
}
void menu()
{
cout<<"\n Viberite:\n";
cout<<"\n1. vvod.";
cout<<"\n2. vivod";
cout<<"\n3. vivod po indeksu.";
cout<<"\n4. kol-vo";
}
void main()
{
array obj(999999);
int i;
while (true)
{
menu();
cin>>i;
clrscr();
switch(i)
{
case 1: obj.Input(); break;
case 2: obj.Output(); break;
case 3: obj.OutputByIndex(); break;
case 4: obj.GetSize(); break;
default : cout<<"\nError!\n" ;
}
}
}
//---------------------------------------------------------------------------
Помогите плз сделать перегрузку операций :
[] Доступ к элементу массива(вывод по индексу)
= Присваивание массива
= = Проверка массивов на равенство
! Удаление всех данных из массива
|
|
|

21.05.2008, 18:08
|
|
Постоянный
Регистрация: 12.04.2007
Сообщений: 413
С нами:
10042776
Репутация:
275
|
|
изменил(добавил код) структуру:
Код:
struct info {
int RegCode;
char FIO[25];
char Address[255];
int INN;
bool equals(const info& obj) {
return ( RegCode == obj.RegCode &&
!strcpy(FIO, obj.FIO) &&
!strcpy(Address, obj.Address) &&
INN == obj.INN
) ;
}
};
Код:
info& operator[](int i) {
if( i < 0 || i >= size ) {
std::cerr << "ArrayOutOfBounds" << std::endl;
} else {
return *(a[i]);
}
}
bool operator==(const info** right) const {
info* curInfo = 0;
for(int i = 0; i < counter; ++i) {
curInfo = a[i];
if( !curInfo->equals(*(right[i])) ) {
return false;
}
}
}
// предполагается что массивы одинаковых размеров
const info** operator=(const info** right) {
for( int i = 0; i < counter; ++i ) {
if( a[i] != 0 ) {
delete a[i];
}
a[i] = new info();
a[i]->RegCode = right[i]->RegCode;
a[i]->INN = right[i]->INN;
strcpy(a[i]->FIO, right[i]->FIO);
strcpy(a[i]->Address, right[i]->Address);
}
return (const info**)a;
}
void operator!() {
if(a == 0) {
return;
}
for( int i = 0; i < counter; ++i ) {
if( a[i] != 0 ) {
delete a[i];
}
}
delete []a;
}
|
|
|

21.05.2008, 20:13
|
|
Участник форума
Регистрация: 24.05.2007
Сообщений: 229
С нами:
9982466
Репутация:
309
|
|
Народ, тут срочно надо решить 2 задачки на Бейсике:
первая: Заданы три стороны треугольника x,y,z. Определить, является ли треугольник прямоугольным. Если да, то опечатать какая сторона служит гипотенузой.
Вторая: заданы длины a,b,c,d четырёх отрезков прямой. Проверить, могут ли эти отрезки быть сторонами квадрута, прямоугольника.
С меня +!!!! Актуально ток сегодня. Плз помогите)
|
|
|

22.05.2008, 00:16
|
|
Участник форума
Регистрация: 06.02.2006
Сообщений: 177
С нами:
10661593
Репутация:
88
|
|
Помогите с задачей, (хотя бы хорошей идеи).
Дана матрица n*n переводов валют.
надо написать алгоритм который за n переводов даёт макс выгоду.
Пояснение: мы должны выйти из какой-то валюты и за n переводов вернутся в неё же.
Валюта с которой начинаются переводы выбирается произвольно(ну то есть надо отыскать ещё валюту из которой наиболее выгодно надо начинать производить переводы)
Вывести путь выгоднейшего перевода
(n<=20)
----------------------
комбинаторика умирает на n=10((((
|
|
|

22.05.2008, 09:24
|
|
Новичок
Регистрация: 08.02.2008
Сообщений: 12
С нами:
9607368
Репутация:
2
|
|
Forcer спс
|
|
|

22.05.2008, 13:01
|
|
Участник форума
Регистрация: 31.10.2007
Сообщений: 213
С нами:
9751512
Репутация:
14
|
|
Вектор задан уравнением типа :
...и дано массив таких векторов !
Напомните какое условие ПАРАЛЛЕЛЬНОСТИ и ПЕРПЕНДИКУЛЯРНОСТИ векторов ??? Помню точно там чтото со СКАЛЯРНОСТЬЮ связано !
Если не трудно - формулу укажите...
Заранее спс .
|
|
|

22.05.2008, 15:47
|
|
Познавший АНТИЧАТ
Регистрация: 27.04.2007
Сообщений: 1,044
С нами:
10021597
Репутация:
905
|
|
Больше смахивает на уравнение прямой, а не вектора
Условие параллельности
Условие перпендикулярности
Код:
A1 * A2 + B1 * B2 = 0
|
|
|

22.05.2008, 20:44
|
|
Новичок
Регистрация: 21.12.2006
Сообщений: 5
С нами:
10203946
Репутация:
0
|
|
Delphi
как сделать эфект пишущегося текста? можно конечно под каждую букву лейбел поставить с задержкой...но это некатит..
|
|
|

22.05.2008, 22:11
|
|
Reservists Of Antichat - Level 6
Регистрация: 04.02.2007
Сообщений: 1,152
С нами:
10139366
Репутация:
1502
|
|
Сообщение от Badanga
Delphi
как сделать эфект пишущегося текста? можно конечно под каждую букву лейбел поставить с задержкой...но это некатит..
Код:
text := 'abcdefghi';
Label1.Caption := '';
for i := 1 to length(text) do
begin
Label1.Caption := Label1.Caption + text[i];
for j := 1 to 10 do
begin
sleep(10);
Application.ProcessMessages;
end;
end;
__________________
Bedankt euch dafür bei euch selbst.
H_2(S^3/((z1, z2)~(exp(2pi*i/p)z1, exp(2pi*q*i/p)z2)))=Z/pZ
|
|
|

22.05.2008, 22:19
|
|
Новичок
Регистрация: 08.02.2008
Сообщений: 12
С нами:
9607368
Репутация:
2
|
|
помогите плз
Описать шаблон контейнерного класса, разработанного в лабораторной работе № 6. Протестировать шаблон для различных типов данных, хранящихся в контейнере. Варианты заданий приведены в табл.
double, структура с полями: шифр книги, авторы, название книги
лаба 6 написанна....вот для нее перегруз...но что то не айс=((
Код:
//---------------------------------------------------------------------------
#pragma hdrstop
//---------------------------------------------------------------------------
#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <vcl.h>
#include <stdio.h>
#pragma argsused
struct info
{
int RegCode;
char FIO[25];
char name[255];
};
template <class t>
class array
{
private:
int size;
t** a;
int counter;
void SetArray( int );
public:
array( int );
array(array &x);
~array();
void Input(t );
void Output();
void OutputByIndex(int);
void GetSize();
array operator !();
array operator =(array );
void operator [](int );
bool operator ==(array);
};
template <class t>
array<t>::array(int size)
{
SetArray(size);
}
template <class t>
array<t>::array (array &x)
{
size=x.size;
counter = x.counter;
a = new t*[size];
for ( int i=0; i < counter; i++)
{
a[i]= x.a[i];
}
}
template <class t>
array<t>::~array()
{
if (a)
delete []a;
}
//--------------------------------------------
template <class t>
void array<t>::SetArray(int siz)
{
a = new t*[siz];
for(int i = 0; i < siz; i++)
{
a[i] = 0;
}
size = siz;
counter = 0;
}
template <class t>
void array<t>::Input(t x)
{
if( counter != size )
{
a[ counter ] = new t;
*a [ counter ] = x;
counter++;
}
else
{
cout << "Error. Array is full";
}
}
template <class t>
void array<t>::Output()
{
if( counter )
{
for( int i = 0; i <counter; i++)
{
cout << "SHifr: " << a[ i ]->RegCode << "\n";
cout << "FIO: " << a[ i ]->FIO << "\n";
cout << "nazvanie: " << a[ i ]->name<< "\n";
cout << "\r\n";
}
}
else
{
cout << "Error. Array is empty"<<endl;
}
}
template <class t>
void array<t>::OutputByIndex(int ind)
{
if( counter )
{
if( ind > counter )
cout << "Error. Index out of range";
else
{
cout << "SHifr: " << a[ ind-1 ]->RegCode << "\n";
cout << "FIO: " << a[ ind -1]->FIO << "\n";
cout << "nazvanie " << a[ ind -1]->name << "\n";
cout << "\r\n"<<endl;
}
}
else
cout << "Array is empty\n"<<endl;
}
template <class t>
void array<t>::GetSize()
{
cout << counter << "\n";
}
//----------------------------------------------
template <class t>
array<t> array<t>::operator =(array<t> x)
{
counter = x.counter;
size = x.size;
a = new t* [size];
for(int i = 0; i < counter; i++)
{
a[i] = x.a[i];
}
return *this;
}
template <class t>
void array<t>::operator [](int ind)
{
OutputByIndex(ind);
}
template <class t>
array<t> array<t>::operator !()
{
if( counter )
{
for( int i = 0; i < counter; i++ )
{
delete a[i];
a[i] = 0;
}
}
counter = 0;
return *this;
}
template <class t>
bool array<t>::operator ==(array<t> x)
{
if (x.counter !=counter)
return false;
for (int i=0;i<counter;i++)
if (a[i]!=x.a[i] )
return false;
return true;
}
void menu()
{
cout << "\n Viberite:\n";
cout << "\n1. vvod ";
cout << "\n2. vivod ";
cout << "\n3. ! Clear array.";
cout << "\n4. = Prisvaivanie." ;
cout << "\n5. [] vivod po indeksu." ;
cout << "\n6. == proverka na ravenstvo." ;
}
int main()
{
int x, ind;
info temp;
cout << "Input array size: ";
cin >> x;
array<double> obj(x);
array<double> obj1(x);
int i;
while (true)
{
menu();
cin>>i;
clrscr();
switch(i)
{
case 1:
cout << "SHifr: ";
cin >> temp.RegCode;
cout << "Input FIO: ";
cin.get();
cin.getline(temp.FIO, 25);
cout << "Input nazvanie: ";
cin.getline(temp.name,255);
obj.Input(temp);
break;
case 2: obj.Output(); break;
case 3: !obj;!obj1; break;
case 4:
obj1 = obj;
obj.Output();
obj1.Output();
break;
case 5:
cout << "Input index: ";
cin >> ind;
obj[ind];
break;
case 6:
if(obj==obj1)
{ cout<<"MHO}|{ECTBA PABHbI"<<endl;
obj.Output();obj1.Output(); }
else
{ cout<<"MHO}|{ECTBA HE PABHbI"<<endl;
obj.Output();obj1.Output(); }
break;
case 0: return 0;
default : cout<<"\nError!\n" ;
}
}
}
|
|
|
|
 |
|
|
Здесь присутствуют: 1 (пользователей: 0 , гостей: 1)
|
|
|
|