fin number



Автор Иван Ларин задал вопрос в разделе Другие языки и технологии

Помогите пожалуйста решить, С++ и получил лучший ответ

Ответ от Cyborg Terminator[гуру]
Вот набросал с использованием хэш-таблицы, а во избежание коллизий реализованы цепочки в виде односвязного списка.
#include <fstream>
#define NUM 128
struct cell {
int key;
cell* next;
};
bool insert_cell(cell* htab[NUM], int key);
void clear_cell(cell* htab[NUM]);
int main(void){
cell* htab[NUM] = {0};
std::ifstream fin("number.txt");
if(! fin.is_open())
return 1;
int num;
while(fin >> num){
insert_cell(htab, num);
}
fin.close();
//...
std::ofstream fout("output.txt");
for(int i = 0; i < NUM; ++i){
for(const cell* p = htab[i]; p != NULL; p = p->next)
fout << p->key << ' ';
}
fout.flush();
fout.close();
clear_cell(htab);
return 0;
}
//вставка в хэш-таблицу
bool insert_cell(cell* htab[NUM], int key){
int ikey = ((key < 0) ? ~key : key) % NUM;
for(const cell* p = htab[ikey]; p != NULL; p = p->next){
if(p->key == key)
return false;
}
cell* node = new cell();
if(node != NULL){
node->key = key;
node->next = htab[ikey];
htab[ikey] = node;
}
return (node != NULL);
}
//удаление всех ячеек хэш-таблицы
void clear_cell(cell* htab[NUM]){
cell* t;
for(int i = 0; i < NUM; ++i){
for(cell* p = htab[i]; p != NULL; ){
t = p;
p = p->next;
delete t;
}
}
}

Ответ от Николай Веселуха[гуру]
#include <iostream> #include <fstream>#include <list>#include <algorithm>using namespace std;int main() { system("chcp 1251 > nul"); ifstream ifs("numbers.txt", ifstream::in); try { if (!ifs) throw runtime_error("numbers.txt"); int number; list<int> numbers; while (ifs >> number) numbers.push_back(number); ofstream ofs("unique.txt", ofstream::out); numbers.sort(); numbers.unique(); try { if (!ofs) throw runtime_error("unique.txt"); while (!numbers.empty()) { ofs << numbers.front(); numbers.pop_front(); if (!numbers.empty()) ofs << ' '; else ofs << '\n'; } ofs.close(); } catch (runtime_error const& e) { cerr << L" Ошибка: Не удаётся записать в файл " << e.what() << endl; ofs.close(); cin.sync(); cin.get(); return -2; } ifs.close(); } catch (runtime_error const& e) { cerr << "\a Ошибка: Не удалось открыть файл " << e.what() << endl; ifs.close(); cin.sync(); cin.get(); return -1; } return 0;}P.S. Если порядок следования элементов не имеет значения

Ответ от 3 ответа[гуру]
Привет! Вот подборка тем с похожими вопросами и ответами на Ваш вопрос: Помогите пожалуйста решить, С++
 

Ответить на вопрос:

Имя*

E-mail:*

Текст ответа:*
Проверочный код(введите 22):*