Telegram Group & Telegram Channel
#advice

"Это как std::vector, но на 20% круче" 🕶

Часто приходится иметь дело с множеством объектов, и также как-то их переупорядочивать, находить в них объект по ключу, и так далее - в зависимости от бизнес-сценария.

Пусть у нас есть объекты класса Meal (блюда ресторана 🍝), тогда обычно несколько блюд представляют так:
std::vector<Meal> meals;

И также где-то находятся методы, которые делают то, что нужно
void SortAlphabetically(std::vector<Meal>& meals);
void SortByCostDesc(std::vector<Meal>& meals);
const Meal* FindMealById(const std::vector<Meal>& meals, std::string_view id);

Это подход уменьшает читабельность кода, потому что множество объектов живет как бы в отрыве от своих методов.

Я несколько раз успешно применял подход - унаследоваться от std::vector и определить там все нужные методы. Получается примерно так:
class MealList : public std::vector<Meal> {
public:
static MealList ParseFromJson(const nlohmann::json& json);

void SortAlphabetically();
void SortByCostDesc();
const Meal* FindMealById(std::string_view id) const;

private:
MealList() = default;
};
И определения методов находятся в соответствующем .cpp-файле.

MealList держит все методы "при себе" и при этом сохраняет всю остальную семантику std::vector (например, возможность range-based for loop).



group-telegram.com/cxx95/43
Create:
Last Update:

#advice

"Это как std::vector, но на 20% круче" 🕶

Часто приходится иметь дело с множеством объектов, и также как-то их переупорядочивать, находить в них объект по ключу, и так далее - в зависимости от бизнес-сценария.

Пусть у нас есть объекты класса Meal (блюда ресторана 🍝), тогда обычно несколько блюд представляют так:

std::vector<Meal> meals;

И также где-то находятся методы, которые делают то, что нужно
void SortAlphabetically(std::vector<Meal>& meals);
void SortByCostDesc(std::vector<Meal>& meals);
const Meal* FindMealById(const std::vector<Meal>& meals, std::string_view id);

Это подход уменьшает читабельность кода, потому что множество объектов живет как бы в отрыве от своих методов.

Я несколько раз успешно применял подход - унаследоваться от std::vector и определить там все нужные методы. Получается примерно так:
class MealList : public std::vector<Meal> {
public:
static MealList ParseFromJson(const nlohmann::json& json);

void SortAlphabetically();
void SortByCostDesc();
const Meal* FindMealById(std::string_view id) const;

private:
MealList() = default;
};
И определения методов находятся в соответствующем .cpp-файле.

MealList держит все методы "при себе" и при этом сохраняет всю остальную семантику std::vector (например, возможность range-based for loop).

BY C++95


Warning: Undefined variable $i in /var/www/group-telegram/post.php on line 260

Share with your friend now:
group-telegram.com/cxx95/43

View MORE
Open in Telegram


Telegram | DID YOU KNOW?

Date: |

"We're seeing really dramatic moves, and it's all really tied to Ukraine right now, and in a secondary way, in terms of interest rates," Octavio Marenzi, CEO of Opimas, told Yahoo Finance Live on Thursday. "This war in Ukraine is going to give the Fed the ammunition, the cover that it needs, to not raise interest rates too quickly. And I think Jay Powell is a very tepid sort of inflation fighter and he's not going to do as much as he needs to do to get that under control. And this seems like an excuse to kick the can further down the road still and not do too much too soon." But because group chats and the channel features are not end-to-end encrypted, Galperin said user privacy is potentially under threat. On February 27th, Durov posted that Channels were becoming a source of unverified information and that the company lacks the ability to check on their veracity. He urged users to be mistrustful of the things shared on Channels, and initially threatened to block the feature in the countries involved for the length of the war, saying that he didn’t want Telegram to be used to aggravate conflict or incite ethnic hatred. He did, however, walk back this plan when it became clear that they had also become a vital communications tool for Ukrainian officials and citizens to help coordinate their resistance and evacuations. "The inflation fire was already hot and now with war-driven inflation added to the mix, it will grow even hotter, setting off a scramble by the world’s central banks to pull back their stimulus earlier than expected," Chris Rupkey, chief economist at FWDBONDS, wrote in an email. "A spike in inflation rates has preceded economic recessions historically and this time prices have soared to levels that once again pose a threat to growth." Messages are not fully encrypted by default. That means the company could, in theory, access the content of the messages, or be forced to hand over the data at the request of a government.
from sg


Telegram C++95
FROM American