Remove elements while looping the containers

Gotchas:
When removing elements from containers, be careful not to saw off the branch on which you are sitting.
There is a big danger that you will remove an element to which your iterator is referring.
For example:
std::map<std::string,float> coll;
...
for (auto pos = coll.begin(); pos != coll.end(); ++pos) {
    if (pos->second == value) {
        coll.erase(pos); // RUNTIME ERROR !!!
    }
}

Calling erase() for the element to which you are referring with pos invalidates pos as an iterator
of coll. Thus, if you use pos after removing its element without any reinitialization, all bets are off.
In fact, calling ++pos results in undefined behavior.

Solution:
(1) Since C++11, erase() always returns the value of the following element.
for (auto pos = coll.begin(); pos != coll.end(); ) {
    if (pos->second == value) {
        pos = coll.erase(pos); // possible only since C++11
    }
    else {
        ++pos;
    }
}

(2) Before C++11, it was a design decision not to return the following position, because if not needed, it costs unnecessary time.
// remove all elements having a certain value
for (pos = coll.begin(); pos != coll.end(); ) {
    if (pos->second == value) {
        coll.erase(pos++);
    }
    else {
        ++pos;
    }
}

### HMIStudio 中 `while` 循环的使用方法 在 HMIStudio 开发环境中,`while` 循环是一种常用的控制结构,用于重复执行某段代码直到满足特定条件为止。以下是关于如何在 HMIStudio 中正确使用 `while` 循环的相关说明。 #### 基本语法 HMIStudio 的脚本语言通常基于 VBScript 或 JavaScript,因此其 `while` 循环的语法规则类似于这些语言: ```vb Dim counter counter = 1 While counter <= 5 ' 执行某些操作 MsgBox "Counter is: " & counter counter = counter + 1 Wend ``` 上述代码展示了如何通过 `while` 循环实现计数器功能[^1]。每次循环都会显示当前计数值,并将其增加 1,直至达到指定的最大值。 #### 定时退出机制 为了防止无限循环,在实际应用中可以设置定时退出逻辑。例如,可以通过引入时间变量来限制循环运行的时间长度。以下是一个简单的例子: ```vb Dim startTime, currentTime, maxTimeInSeconds startTime = Timer() maxTimeInSeconds = 10 While True currentTime = Timer() If (currentTime - startTime) >= maxTimeInSeconds Then Exit While End If ' 这里放置需要反复执行的任务 MsgBox "Looping..." Wend ``` 此示例中的 `Timer()` 函数返回自午夜以来经过的秒数,从而允许程序计算已花费的时间并决定何时停止循环[^2]。 #### 实际应用场景 假设我们需要开发一个监控系统状态的小工具,该工具每隔一秒读取一次设备的状态数据,并当检测到异常情况时发出警报,则可以用如下方式编写代码: ```vb Dim statusFlag statusFlag = False While Not statusFlag Call ReadDeviceStatus(statusFlag) WScript.Sleep(1000) ' 每隔一秒检查一次 Wend If statusFlag Then MsgBox "Warning! Device has an issue." End If ``` 这里调用了假想函数 `ReadDeviceStatus` 来模拟获取外部硬件的信息过程;同时利用了 `WScript.Sleep` 方法让线程暂停一段时间再继续下一轮迭代。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值