108 lines
2.4 KiB
Markdown
108 lines
2.4 KiB
Markdown
|
---
|
|||
|
title: "Полезности"
|
|||
|
categories: ["cpp", "archive"]
|
|||
|
date: 2015-12-01T00:00:00+03:00
|
|||
|
draft: false
|
|||
|
featured_image: miniature.jpg
|
|||
|
---
|
|||
|
|
|||
|
|
|||
|
На этой страничке я собираю все полезные кусочки кодов, которые мне пригождаются.
|
|||
|
|
|||
|
<!--more-->
|
|||
|
|
|||
|
# С/С++:
|
|||
|
|
|||
|
|
|||
|
## Вывод списка файлов в папке, dirent:
|
|||
|
|
|||
|
```c
|
|||
|
DIR *dir;
|
|||
|
struct dirent *ent;
|
|||
|
if (dir = opendir ("mydir")) {
|
|||
|
while (ent = readdir (dir)) {
|
|||
|
printf ("%s\n", ent->d_name);
|
|||
|
}
|
|||
|
closedir (dir);
|
|||
|
}
|
|||
|
```
|
|||
|
|
|||
|
## Удаление элементов вектора во время итерации:
|
|||
|
|
|||
|
```cpp
|
|||
|
vector< string >::iterator it = curFiles.begin();
|
|||
|
|
|||
|
while(it != curFiles.end()) {
|
|||
|
if(something) {
|
|||
|
it = curFiles.erase(it);
|
|||
|
} else ++it;
|
|||
|
}
|
|||
|
```
|
|||
|
|
|||
|
## Освобождение памяти вектора:
|
|||
|
|
|||
|
```cpp
|
|||
|
struct delete_ptr {
|
|||
|
template <typename P>
|
|||
|
void operator () (P p) {
|
|||
|
delete p;
|
|||
|
}
|
|||
|
};
|
|||
|
|
|||
|
std::for_each(myvector.begin(), myvector.end(), delete_ptr());
|
|||
|
myvector.clear();
|
|||
|
```
|
|||
|
|
|||
|
## Построковое чтение файла:
|
|||
|
|
|||
|
```c
|
|||
|
const char filename[] = "file.txt";
|
|||
|
FILE *file = fopen(filename, "r");
|
|||
|
if (file != NULL) {
|
|||
|
char line[128];
|
|||
|
while (fgets(line, sizeof line, file) != NULL)
|
|||
|
{
|
|||
|
fputs(line, stdout);
|
|||
|
}
|
|||
|
fclose(file);
|
|||
|
}
|
|||
|
```
|
|||
|
|
|||
|
## OpenGL, рисование цветных прямоугольников:
|
|||
|
|
|||
|
```cpp
|
|||
|
void drawRect(int x1, int y1, int x2, int y2, int color) {
|
|||
|
float alpha = (float) (color >> 24 & 255) / 255.0F;
|
|||
|
float red = (float) (color >> 16 & 255) / 255.0F;
|
|||
|
float green = (float) (color >> 8 & 255) / 255.0F;
|
|||
|
float blue = (float) (color & 255) / 255.0F;
|
|||
|
glColor4f(red, green, blue, alpha);
|
|||
|
glBegin(GL_QUADS);
|
|||
|
glVertex3f(x1, y2, 0.0F);
|
|||
|
glVertex3f(x2, y2, 0.0F);
|
|||
|
glVertex3f(x2, y1, 0.0F);
|
|||
|
glVertex3f(x1, y1, 0.0F);
|
|||
|
glEnd();
|
|||
|
}
|
|||
|
|
|||
|
void drawRectAt(int x, int y, int width, int height, int color) {
|
|||
|
drawRect(x, y, x + width, x + height, color);
|
|||
|
}
|
|||
|
|
|||
|
void drawPixel(int x, int y, int color) {
|
|||
|
drawRect(x, y, x + 1, y + 1, color);
|
|||
|
}
|
|||
|
```
|
|||
|
|
|||
|
## Количество дней в месяце (с учётом високостного года):
|
|||
|
|
|||
|
```c
|
|||
|
int get_month_days(int year, int month){
|
|||
|
if (month == 4 || month == 6 || month == 9 || month == 11){
|
|||
|
return 30;
|
|||
|
} else if (month == 2) {
|
|||
|
return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) ? 29 : 28;
|
|||
|
} else return 31;
|
|||
|
}
|
|||
|
```
|