c++ - 有什么方法可以检查迭代器是否有效?

标签 c++ performance stl iterator

例如,对于操作容器映射的两个线程,测试迭代器是否仍然有效(出于性能原因)的正确方法是什么?
或者只是间接的方式可以做到这一点。 示例代码:

#define _SECURE_SCL 1
//http://msdn2.microsoft.com/en-us/library/aa985973.aspx
#define _SECURE_SCL_THROWS 1

#include "map"
#include "string"
#include "exception"
#include "iostream"

using namespace std;

void main(void)
{
    map<string, string> map_test;
    map<string, string>::iterator iter_map_test;

    map_test [ "AAAAA" ] = "11111";
    map_test [ "BBBBB" ] = "22222";
    map_test [ "CCCCC" ] = "33333";

    iter_map_test = map_test.find ("BBBBB");

    map_test.erase ("BBBBB");

    try
    {
        string value = (*iter_map_test).second;
    }
    catch ( exception & e )
    {
            cout << e.what() << endl;
    }
    catch ( ... )
    {
            cout << "generic exception." << endl;
    }
}

最佳答案

std::map 根本不是线程安全的。如果您同时有多个线程修改同一映射,您最终会遇到比无效迭代器更糟糕的问题。我什至认为您不能保证在 map 被另一个线程修改时可以从 map 中读取任何内容。

一些关于STL和线程的页面:

关于c++ - 有什么方法可以检查迭代器是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/436013/

相关文章:

c++ - 我可以将参数传递给 std::vector 排序函数吗?

c++ - 静态与成员运算符重载:std::operator<< 和 std::ostream::operator<<

c++ - 使用 Makefile 的交叉编译使用了错误的包含

c++ - BFS 算法 - 具有约束步骤的网格上的最短步行

php - PHP 函数的 Big-O 列表

performance - Propel 2 和 Doctrine 2 有详细的比较吗

c++ - 通过 RS485 通讯

Java 性能 - 如何以高性能将大数组写入磁盘/SD 卡?

c++ - 我想根据自己的参数使用 count_if

c++ - 如何在 std::map 中存储混合类型项目?