\r
перемещает вывод на начало последней строки, при этом дальнейший вывод идёт поверх неё, что нам и нужно. Так что: считываем строку, меняем её, как душе угодно, выводим \r
, выводим модифицированную строку. enum Foo {
case qqq(Int)
case www(Int)
}
let x = Foo.qqq(5)
let y = Foo.www(10)
class Foo {
public:
virtual ~Foo() = 0;
};
class qqq : public Foo {
public:
int value;
explicit qqq(int value);
};
class www : public Foo {
public:
int value;
explicit www(int value);
};
using FooPtr = std::unique_ptr<Foo>;
FooPtr makeQqq(int value);
FooPtr makeWww(int value);
FooPtr x = makeQqq(5);
FooPtr y = makeWww(10);
type_safe
(кликабельно).#include <type_safe/strong_typedef.hpp>
#include <type_safe/variant.hpp>
namespace ts = type_safe;
using qqq = ts::strong_typedef<int>;
using www = ts::strong_typedef<int>;
using Foo = ts::variant<qqq, www>;
// ...
auto x = Foo(qqq(5));
auto y = Foo(www(10));
if (x.has_value(ts::variant_type<qqq>{})) {
qqq value = x.value(ts::variant_type<qqq>{}));
std::cout << "qqq" << ' ' << static_cast<int>(value);
}
char*
- это по соглашению Си-строка, то есть указатель на буфер символов, оканчивающийся нулевым байтом '\0'. Для любого типа T
, кроме, вероятно, char
, T*
может быть массивом, а именно, указателем на его первый элемент. Соответственно, char** s
- это, скорее всего, массив строк. s[2]
- это указатель на третью строку, s[2][3]
- это четвёртый символ третьей строки. #include <iostream>
#include <array>
template<typename T, size_t n>
constexpr T& at(std::array<T, n>& a, size_t i) {
return const_cast<T&>(static_cast<const std::array<T, n>&>(a)[i]);
}
template<typename T, size_t n>
constexpr const T& at(const std::array<T, n>& a, size_t i) {
return a[i];
}
constexpr std::array<int, 20> generate_fib() {
auto result = std::array<int, 20>{};
for (size_t i = 0; i < 20; ++i) {
if (i < 2) {
at(result, i) = 1;
} else {
at(result, i) = at(result, i-1) + at(result, i-2);
}
}
return result;
}
constexpr static const auto fib = generate_fib();
int main()
{
for (auto elem : fib) {
std::cout << elem << ' ';
}
return 0;
}
char s1[7] = "hello";
struct Child {
int data;
};
struct Parent {
struct Child* child;
};
struct Child createChild(struct Parent* parent) {
struct Child result;
parent->child = &result;
return result; // parent->child будет указывать на мусор :(
}
type
-- это имя типа вашего enum. var
-- название переменной только что объявленного типа. Код можно переписать так:enum type {
A,B,C
};
enum type var;
type
-- это ключевое слово, лучше классический enum fruit { apple, orange };
. Плюс определять переменные в объявлении типа -- advanced feature, я бы её в первом же примере не давал. signed int num = INT_MAX;
Тогда при ++num;
что окажется в num
-- unspecified. То есть может оказаться INT_MIN, а может 42.unsigned int num = UINT_MAX;
Тогда при ++num;
в num
обязано оказаться 0
, в соответствии со стандартом. переполнения беззнаковых целых быть не должно
#include <vector>
#include <random>
std::vector<double> result(100);
std::uniform_real_distribution<double> unif(-10.0, 10.0);
std::default_random_engine re;
for (int i = 0; i < 100; ++i) {
result[i] = unif(re);
}
std::sort(result.begin(), result.end());
scanf("%d", &airport[i].numr);
// =>
scanf("%d\n", &airport[i].numr);
printf("\n%d", airport[i].numr);
// =>
printf("%d\n", airport[i].numr);
int compare_prices(const void* price1, const void* price2) {
const char* name1 = ((const price*)price1)->name;
const char* name2 = ((const price*)price2)->name;
return strcmp(name1, name2);
}
qsort(МАССИВ_СТРУКТУР, РАЗМЕР_МАССИВА, sizeof(price), &compare_prices);
std::string
не имелся в виду.char*
, хотя это тип указателя на один char
.char[8]
, принято передавать как указатель на его первый элемент: char*
. Более того, при передаче массива в функцию он автоматически разлагается (decays) до указателя на первый элемент.*(p+3)
или p[3]
, что одно и то же. Итак, указатель в коде C может указывать как на одну переменную, так и на целый массив (точнее, его начало).int
или любого другого типа обычно вместе с указателем на первый элемент передают размер массива. Но строки C завершаются нулевым символом, поэтому здесь длина известна и так. Вот и получается, что char*
используют вместо char[N]
.int (*arr)[10] = malloc(sizeof(*arr) * 5);
#include <stdlib.h>
#include <stdio.h>
struct TNode {
int data;
struct TNode *next;
};
typedef struct TNode Node;
struct TQueue {
Node* head;
Node* tail;
};
typedef struct TQueue Queue;
Queue* newQueue()
{
Queue* queue = malloc(sizeof(Queue));
queue->head = NULL;
queue->tail = NULL;
return queue;
}
void deleteQueue(Queue* queue)
{
Node* current = queue->head;
while (current != NULL) {
Node* next = current->next;
free(current);
current = next;
}
free(queue);
}
void pushBackQueue(Queue* queue, int data)
{
Node* newNode = malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (queue->tail == NULL) {
queue->head = newNode;
queue->tail = newNode;
}
else {
queue->tail->next = newNode;
queue->tail = newNode;
}
}
void splitQueue(Queue* source, Queue* even, Queue* odd)
{
for (Node* current = source->head; current != NULL; current = current->next) {
int data = current->data;
pushBackQueue((data % 2 == 0) ? even : odd, data);
}
}
void printQueue(Queue* queue)
{
for (Node* current = queue->head; current != NULL; current = current->next) {
printf("%d ", current->data);
}
printf("\n");
}
int main()
{
Queue* source = newQueue();
for (int i = 0; i < 20; i++) {
pushBackQueue(source, i + 1);
}
printQueue(source);
Queue* even = newQueue();
Queue* odd = newQueue();
splitQueue(source, even, odd);
printQueue(even);
printQueue(odd);
deleteQueue(source);
deleteQueue(even);
deleteQueue(odd);
system("pause"); // not needed in Linux
return 1;
}