有没有办法检查迭代器是否有效? [英] Is there any way to check if an iterator is valid?

查看:246
本文介绍了有没有办法检查迭代器是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于两个操作容器映射的线程,例如,测试迭代器是否仍然有效的正确方法是什么(出于性能原因)?

或者只是间接的方式可以完成这个。
此示例代码:

For two threads manipulating a container map for example, what the correct way to test whether an iterator still valid (for performance reason) ?
Or would be of only indirect way that this can be done. The sample code for this :

#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 s根本不是线程安全的。如果一次有多个线程修改同一个映射,那么最终会遇到比失效迭代器更糟糕的问题。我甚至认为你无法保证在被另一个线程修改时你可以从地图中读取任何内容。

std::maps are not at all thread-safe. You'll end up with much worse problems than invalidated iterators, if you have more than one thread at a time modifying the same map. I don't even think you have a guarantee that you can read anything out of a map while it's being modified by another thread.

STL和线程上的一些页面:

Some pages on the STL and threading:

  • MSDN
  • SGI
  • GCC

这篇关于有没有办法检查迭代器是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆