Warning: mkdir(): No space left on device in /var/www/tgoop/post.php on line 37

Warning: file_put_contents(aCache/aDaily/post/cpp_geek/--): Failed to open stream: No such file or directory in /var/www/tgoop/post.php on line 50
C++ geek@cpp_geek P.321
CPP_GEEK Telegram 321
Тонкости 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



tgoop.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


Share with your friend now:
tgoop.com/cpp_geek/321

View MORE
Open in Telegram


Telegram News

Date: |

Telegram channels enable users to broadcast messages to multiple users simultaneously. Like on social media, users need to subscribe to your channel to get access to your content published by one or more administrators. Commenting about the court's concerns about the spread of false information related to the elections, Minister Fachin noted Brazil is "facing circumstances that could put Brazil's democracy at risk." During the meeting, the information technology secretary at the TSE, Julio Valente, put forward a list of requests the court believes will disinformation. Add the logo from your device. Adjust the visible area of your image. Congratulations! Now your Telegram channel has a face Click “Save”.! Although some crypto traders have moved toward screaming as a coping mechanism, several mental health experts call this therapy a pseudoscience. The crypto community finds its way to engage in one or the other way and share its feelings with other fellow members. Telegram users themselves will be able to flag and report potentially false content.
from us


Telegram C++ geek
FROM American