C/C++

В файле записано не более 100 чисел. Отсортировать их по возрастанию последней цифры и записать в другой файл.

#include <iostream>
#include <set>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
class Token {
public:
int& ref() {
return token;
}
private:
int token;
friend bool operator<(const Token& a, const Token& b) {
auto x = a.token % 10;
auto y = b.token % 10;
if (x == y) return a.token < b.token;
return x < y;
}
friend istream& operator>>(istream& inp, Token& t) {
return inp >> t.token;
}
friend ostream& operator<<(ostream& inp, const Token& t) {
return inp << t.token;
}
};
int main() {
ifstream file("file.txt");
ofstream other("other.txt");
if (file.is_open()) {
multiset<Token> box;
string line;
while (getline(file, line)) {
istringstream iss(line);
Token token;
while (iss >> token.ref()) box.insert(token);
}
ofstream other("other.txt");
if (other.is_open()) {
for (const auto& x : box) other << x << ' ';
other << '\n';
}
}
file.is_open() ? file.close() : void();
other.is_open() ? other.close() : void();
}
Aziz Dushamov
Aziz Dushamov
73 697
Лучший ответ
Сортировка не нужна: можно же сразу раскидывать числа в 10 списков по последней цифре. А потом последовательно вывести списки в выходной файл.

var
buf: array[0..9, 0..99] of integer;
len: array[0..9] of integer;
i, j: integer;
f: text;
begin
assign(f, 'input.txt');
reset(f);
while not eof(f) do begin
readln(f, i);
j := abs(i) mod 10;
buf[j][len[j]] := i;
inc(len[j])
end;
close(f);
assign(f, 'output.txt');
rewrite(f);
for i := 0 to 9 do for j := 0 to len[i] - 1 do writeln(f, buf[i][j]);
close(f)
end.
const
n=100;
var
a:array[1..n] of integer;
k,i,j,r:integer;
t:text;
begin
assign(t,'c:\input.txt');reset(t);
k:=0;
writeln('Исходный массив');
while not eof(t) do
begin
k:=k+1;
read(t,a[k]);
writeln(a[k]:8);
end;
writeln;
close(t);
for i:=1 to k-1 do
for j:=1 to k-i do
if (a[j] mod 10)>(a[j+1] mod 10) then
begin
r:=a[j];a[j]:=a[j+1];a[j+1]:=r;
end;
assign(t,'c:\output.txt');rewrite(t);
writeln('Отсортированный массив');
for i:=1 to k do begin
writeln(t,a[i]);
writeln(a[i]:8);
end;
readln;
close(t)
end.
...и записать в другой файл, в дате создания которого число месяца делится без остатка на номер домашнего задания... :)
Андрей Князев
Андрей Князев
37 945