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: |

Why Telegram?

Telegram has no known backdoors and, even though it is come in for criticism for using proprietary encryption methods instead of open-source ones, those have yet to be compromised. While no messaging app can guarantee a 100% impermeable defense against determined attackers, Telegram is vulnerabilities are few and either theoretical or based on spoof files fooling users into actively enabling an attack.

The global forecast for the Asian markets is murky following recent volatility, with crude oil prices providing support in what has been an otherwise tough month. The European markets were down and the U.S. bourses were mixed and flat and the Asian markets figure to split the difference.The TSE finished modestly lower on Friday following losses from the financial shares and property stocks.For the day, the index sank 15.09 points or 0.49 percent to finish at 3,061.35 after trading between 3,057.84 and 3,089.78. Volume was 1.39 billion shares worth 1.30 billion Singapore dollars. There were 285 decliners and 184 gainers.

telegram from jp


Telegram C++ geek
FROM USA