【问题标题】:Arithmetic with concurrent_vector iterators: is it safe to assume that subtracting 'begin ()' from an iterator will give the index?concurrent_vector 迭代器的算术:假设从迭代器中减去“begin ()”会给出索引是否安全?
【发布时间】:2013-05-01 11:12:49
【问题描述】:

由于 concurrent_vector 不使用连续的内存块,我想确定这是否可以:

concurrency::concurrent_vector<Something> my_array;

//Populate 'm_array' somehow perhaps involving multiple threads

const auto iter  = std::find_if (my_array.begin (), m_array.end (), SomeLambda);
const int  index = iter - my_array.begin ();

我的问题:在任何情况下,'index' 不会索引我刚刚找到的元素(通过 concurrect_vector::operator[] 方法)?我意识到另一个线程理论上可以修改元素 - 这不是我的问题。

我想这应该可行,但是因为我习惯于使用原始指针,所以我想问一下(这样我就不会无意中添加细微错误的来源)。

【问题讨论】:

标签: c++ multithreading visual-c++ concurrency iterator


【解决方案1】:

concurrent_vector::iterator 是一个随机访问迭代器,因此支持并有效地取差(尽管您不应该使用int 来存储结果)。

当然,正如您所说,这不是线程安全的。

【讨论】:

  • 谢谢@Joe。我将根据这个答案继续编写我的代码。也感谢您修改问题 - 我没有意识到 concurrent_vector 是 Microsoft 特定的,但这仍然很好,因为我只在 Visual Studio 中编写代码。
  • @Coder_Dan 它似乎并没有给std::vector 增加很多东西。如果你想要可移植的代码,你可以很容易地编写这个功能。话虽如此,其他人可能已经这样做了。
【解决方案2】:

它是安全的,但为什么不使用std::distance呢?

  • 它更惯用。
  • 如果您更换容器,它将起作用。
  • 同样高效。

【讨论】:

  • 谢谢@Alex。我是 STL 的新手,之前没有遇到过 std::distance。
猜你喜欢
  • 2012-07-02
  • 2021-03-18
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
相关资源
最近更新 更多