在C++98标准下,可以使用迭代器来遍历和删除std::map中的元素。以下是一个示例代码:

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> compress_task;
    compress_task["file1"] = 1;
    compress_task["file2"] = 2;
    compress_task["file3"] = 3;

    std::map<std::string, int>::iterator it = compress_task.begin();
    while (it != compress_task.end()) {
        if (it->second == 2) {
            compress_task.erase(it++);
        } else {
            ++it;
        }
    }

    // 遍历输出
    for (it = compress_task.begin(); it != compress_task.end(); ++it) {
        std::cout << it->first << ": " << it->second << std::endl;
    }

    return 0;
}

在上述示例中,我们首先创建了一个std::map对象compress_task,并添加了一些键值对。然后,我们使用迭代器it来遍历std::map,如果某个元素的值等于2,则使用erase函数删除该元素,并将迭代器it递增。最后,我们再次使用迭代器it来遍历输出剩余的元素。

注意,在C++98标准中,erase函数会返回下一个元素的迭代器,所以我们需要在erase函数之后将迭代器it递增。

linux c++ static stdmapstdstring int compress_task; 遍历删除使用 c++98标准 怎么实现

原文地址: https://www.cveoy.top/t/topic/jc8p 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录