ЛИСТИНГ
1. Код первого задания. С С++
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TITLE 100
#define MAX_AUTHOR 100
typedef struct {
char title[MAX_TITLE];
char author[MAX_AUTHOR];
int year;
} Book;
Book* add_book(Book* books, int* count,
const char* title, const char* author, int year) {
books = realloc(books, (*count + 1) * sizeof(Book));
if (!books) {
fprintf(stderr, "Memory allocation error\n");
exit(1);
}
strncpy(books[*count].title, title, MAX_TITLE - 1);
books[*count].title[MAX_TITLE - 1] = '\0';
strncpy(books[*count].author, author, MAX_AUTHOR - 1);
books[*count].author[MAX_AUTHOR - 1] = '\0';
books[*count].year = year;
(*count)++;
return books;
}
void print_books(const Book* books, int count) {
for (int i = 0; i < count; i++) {
printf("\"%s\" by %s (%d)\n",
books[i].title, books[i].author, books[i].year);
}
}
int cmp_by_year(const void* a, const void* b) {
return ((Book*)a)->year - ((Book*)b)->year;
}
int main() {
Book* library = NULL;
int count = 0;
library = add_book(library, &count,
"The C Programming Language", "K&R", 1978);
library = add_book(library, &count,
"Clean Code", "Robert C. Martin", 2008);
library = add_book(library, &count,
"Design Patterns", "GoF", 1994);
printf("Before sorting:\n");
print_books(library, count);
qsort(library, count, sizeof(Book), cmp_by_year);
printf("\nSorted by year:\n");
print_books(library, count);
free(library);
return 0;
}
2. Код первого задания. С ++ С
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
class Book {
public:
std::string title;
std::string author;
int year;
Book(std::string t, std::string a, int y)
: title(std::move(t)), author(std::move(a)), year(y) {}
friend std::ostream& operator<<(std::ostream& os, const Book& b) {
os << '"' << b.title << "\" by " << b.author << " (" << b.year << ')';
return os;
}
};
int main() {
std::vector<Book> library;
library.emplace_back("The C++ Programming Language",
"Bjarne Stroustrup", 2013);
library.emplace_back("Effective Modern C++",
"Scott Meyers", 2014);
library.emplace_back("The Art of Computer Programming",
"Donald Knuth", 1968);
std::cout << "Before sorting:\n";
for (const auto& book : library)
std::cout << book << '\n';
std::sort(library.begin(), library.end(),
[](const Book& a, const Book& b) { return a.year < b.year; });
std::cout << "\nSorted by year:\n";
for (const auto& book : library)
std::cout << book << '\n';
return 0;
}
3. Код первого задания. С С++
#include <iostream>
#include <string>
#include <map>
#include <sstream>
#include <iomanip>
int main() {
std::string text = "hello world hello c++ world";
std::map<std::string, int> freq;
std::istringstream iss(text);
std::string word;
while (iss >> word) {
++freq[word];
}
for (const auto& p : freq) {
std::cout << std::setw(10) << p.first << ": " << p.second << '\n';
}
return 0;
}