Изучаем C++.
Ресурсы, обучения, задачи, шпаргалки.
Вопросы с собеседований по C++ и ответы на них.
Задачи и тесты по C++ для тренировки и обучения.
По рекламе: @anothertechrock
Post #266
271
УЮ @cppturbo
Showing posts older than #268 · Back to latest



int array[] = {1, 2, 3, 4, 5};
int *ptr = array;
for(int i = 0; i < 5; i++) {
printf(«%d «, *ptr); ptr++;
}
// Вывод: 1 2 3 4 5
; считаются разными строчками.int count_ones(unsigned num) {
// Here your code
}






struct Queue {
void push(int value) {
storage.push_back(value);
}
void pop() {
storage.pop_front();
}
bool empty() {
return storage.empty();
}
int& front() {
return storage.front();
}
private:
std::deque<int> storage;
};while(condition)
if (!queue.empty()) {
auto & elem = queue.front();
process_elem(elem);
queue.pop();
}
struct Queue {
void push(int value) {
std::lock_guard lg{m};
storage.push_back(value);
}
void pop() {
std::lock_guard lg{m};
storage.pop_front();
}
bool empty() {
std::lock_guard lg{m};
return storage.empty();
}
int& front() {
std::lock_guard lg{m};
return storage.front();
}
private:
std::deque<int> storage;
std::mutex m;
};while(true)
if (!queue.empty()) {
auto & elem = queue.front();
process_elem(elem);
queue.pop();
}
struct ThreadSafeQueue {
void push(int value) {
std::lock_guard lg{m};
storage.push_back(value);
}
std::optional<int> pop() {
std::lock_guard lg{m};
if (!storage.empty()) {
int elem = storage.front();
storage.pop_front();
return elem;
}
return nullopt;
}
private:
std::deque<int> storage;
std::mutex m;
};pop мы можем использовать проверять и получать стейт очереди, так как мы оградились локом. Возвращаем из него std::optional, который будет хранить фронтальный элемент, если очередь была непуста. В обратном случае он будет пуст.while(true) {
auto elem = queue.pop();
if (elem)
process_elem(elem.value());
}

#include <iostream>
void foo(int a) { std::cout << "int"; }
void foo(char a) { std::cout << "char"; }
int main() {
foo(97);
return 0;
}
int, поэтому вызывается версия foo(int). 'a' (символьный литерал), то вызвалась бы foo(char).unsigned char, то могла бы произойти неявная конверсия, но тут всё однозначно! 😊