Telegram Group & Telegram Channel
Тонкости STL, которые часто вылетают в продакшн:

1. Инвалидирование итераторов
При vector::erase все итераторы от позиции удаления до end() становятся «битые». Чтобы безопасно отфильтровать и удалить элементы, пользуйтесь erase–remove идиомой:


auto it = std::remove_if(v.begin(), v.end(), [](int x){ return x < 0; });
v.erase(it, v.end());


remove_if сдвигает «хвост» вперёд, но не меняет размер контейнера.

2. reserve vs resize

* v.reserve(n) выделяет память, но не создаёт объектов → size() не меняется, можно безопасно push_back.
* v.resize(n) создаёт n элементов, инициализированных значениями по умолчанию.

3. Производительность std::distance
На random-access итераторах (например, vector) это O(1), а на bidirectional или forward (например, list) — O(n). Для списков используйте size() (C++11+) или считайте вручную в критичных местах.

4. emplace_back vs push_back
При сложных типах emplace_back может избежать лишнего копирования:


v.emplace_back(ctor_arg1, ctor_arg2);
// vs
v.push_back(MyType(ctor_arg1, ctor_arg2));


5. Памятка про компараторы
В set или map ваш компаратор должен задавать строгий-уровень-менее (operator<): если comp(a,b)==true, то comp(b,a) обязан быть false. Иначе — UB.

Быстро, без воды, но с пользой — проверяйте эти моменты в своём коде!

➡️ @cpp_geek



tg-me.com/cpp_geek/321
Create:
Last Update:

Тонкости STL, которые часто вылетают в продакшн:

1. Инвалидирование итераторов
При vector::erase все итераторы от позиции удаления до end() становятся «битые». Чтобы безопасно отфильтровать и удалить элементы, пользуйтесь erase–remove идиомой:


auto it = std::remove_if(v.begin(), v.end(), [](int x){ return x < 0; });
v.erase(it, v.end());


remove_if сдвигает «хвост» вперёд, но не меняет размер контейнера.

2. reserve vs resize

* v.reserve(n) выделяет память, но не создаёт объектов → size() не меняется, можно безопасно push_back.
* v.resize(n) создаёт n элементов, инициализированных значениями по умолчанию.

3. Производительность std::distance
На random-access итераторах (например, vector) это O(1), а на bidirectional или forward (например, list) — O(n). Для списков используйте size() (C++11+) или считайте вручную в критичных местах.

4. emplace_back vs push_back
При сложных типах emplace_back может избежать лишнего копирования:


v.emplace_back(ctor_arg1, ctor_arg2);
// vs
v.push_back(MyType(ctor_arg1, ctor_arg2));


5. Памятка про компараторы
В set или map ваш компаратор должен задавать строгий-уровень-менее (operator<): если comp(a,b)==true, то comp(b,a) обязан быть false. Иначе — UB.

Быстро, без воды, но с пользой — проверяйте эти моменты в своём коде!

➡️ @cpp_geek

BY C++ geek


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/cpp_geek/321

View MORE
Open in Telegram


telegram Telegram | DID YOU KNOW?

Date: |

Telegram and Signal Havens for Right-Wing Extremists

Since the violent storming of Capitol Hill and subsequent ban of former U.S. President Donald Trump from Facebook and Twitter, the removal of Parler from Amazon’s servers, and the de-platforming of incendiary right-wing content, messaging services Telegram and Signal have seen a deluge of new users. In January alone, Telegram reported 90 million new accounts. Its founder, Pavel Durov, described this as “the largest digital migration in human history.” Signal reportedly doubled its user base to 40 million people and became the most downloaded app in 70 countries. The two services rely on encryption to protect the privacy of user communication, which has made them popular with protesters seeking to conceal their identities against repressive governments in places like Belarus, Hong Kong, and Iran. But the same encryption technology has also made them a favored communication tool for criminals and terrorist groups, including al Qaeda and the Islamic State.

Start with a fresh view of investing strategy. The combination of risks and fads this quarter looks to be topping. That means the future is ready to move in.Likely, there will not be a wholesale shift. Company actions will aim to benefit from economic growth, inflationary pressures and a return of market-determined interest rates. In turn, all of that should drive the stock market and investment returns higher.

telegram from it


Telegram C++ geek
FROM USA