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

How Does Bitcoin Mining Work?

Bitcoin mining is the process of adding new transactions to the Bitcoin blockchain. It’s a tough job. People who choose to mine Bitcoin use a process called proof of work, deploying computers in a race to solve mathematical puzzles that verify transactions.To entice miners to keep racing to solve the puzzles and support the overall system, the Bitcoin code rewards miners with new Bitcoins. “This is how new coins are created” and new transactions are added to the blockchain, says Okoro.

The Singapore stock market has alternated between positive and negative finishes through the last five trading days since the end of the two-day winning streak in which it had added more than a dozen points or 0.4 percent. The Straits Times Index now sits just above the 3,060-point plateau and it's likely to see a narrow trading range on Monday.

telegram from it


Telegram C++ geek
FROM USA