Telegram Group & Telegram Channel
🔥 Сегодня я расскажу про одно коварное поведение std::vector, которое часто становится причиной багов и утечек.

📌 Проблема: Удаление элементов в цикле

Многие делают так:


std::vector<int> v = {1, 2, 3, 4, 5};

for (size_t i = 0; i < v.size(); ++i) {
if (v[i] % 2 == 0) {
v.erase(v.begin() + i);
}
}


Но это ошибка! После erase вектор сдвигает все элементы, и индекс i указывает уже не на тот элемент. В результате часть значений пропускается.

Правильный способ — использовать итераторы:


auto it = v.begin();
while (it != v.end()) {
if (*it % 2 == 0)
it = v.erase(it);
else
++it;
}


Так вы не теряете элементы и не получаете неопределённое поведение.

🧠 Советы:
- Всегда помните, что erase инвалидирует итераторы и индексы.
- Если хотите удалять по условию — лучше использовать std::remove_if + erase.


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


➡️ @cpp_geek



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

🔥 Сегодня я расскажу про одно коварное поведение std::vector, которое часто становится причиной багов и утечек.

📌 Проблема: Удаление элементов в цикле

Многие делают так:


std::vector<int> v = {1, 2, 3, 4, 5};

for (size_t i = 0; i < v.size(); ++i) {
if (v[i] % 2 == 0) {
v.erase(v.begin() + i);
}
}


Но это ошибка! После erase вектор сдвигает все элементы, и индекс i указывает уже не на тот элемент. В результате часть значений пропускается.

Правильный способ — использовать итераторы:


auto it = v.begin();
while (it != v.end()) {
if (*it % 2 == 0)
it = v.erase(it);
else
++it;
}


Так вы не теряете элементы и не получаете неопределённое поведение.

🧠 Советы:
- Всегда помните, что erase инвалидирует итераторы и индексы.
- Если хотите удалять по условию — лучше использовать std::remove_if + erase.


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


➡️ @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/309

View MORE
Open in Telegram


telegram Telegram | DID YOU KNOW?

Date: |

In many cases, the content resembled that of the marketplaces found on the dark web, a group of hidden websites that are popular among hackers and accessed using specific anonymising software.“We have recently been witnessing a 100 per cent-plus rise in Telegram usage by cybercriminals,” said Tal Samra, cyber threat analyst at Cyberint.The rise in nefarious activity comes as users flocked to the encrypted chat app earlier this year after changes to the privacy policy of Facebook-owned rival WhatsApp prompted many to seek out alternatives.

Tata Power whose core business is to generate, transmit and distribute electricity has made no money to investors in the last one decade. That is a big blunder considering it is one of the largest power generation companies in the country. One of the reasons is the company's huge debt levels which stood at ₹43,559 crore at the end of March 2021 compared to the company’s market capitalisation of ₹44,447 crore.

telegram from ye


Telegram C++ geek
FROM USA