gpt4 book ai didi

c++ - 测试两个迭代器是否来自同一个对象

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:37:15 24 4
gpt4 key购买 nike

给定两个相同类型的 std::iterators,如何测试它们是否来自同一个对象(而不是类)?请注意,我不是在问如何比较它们的值。

std::string foo = "foo";
std::string bar = "bar";

std::string::iterator iter1 = foo.begin();
std::string::iterator iter2 = bar.begin();

if ( iter1 == iter2 )
{
...
}

以上应该并且确实失败了。我如何在运行时检查这个?查看源代码,我看到相关方法调用 iterator::_Compat() 这是一个 void 方法,它执行我想要的检查,但失败时它会发出调试断言。它在发布版本中不会被注意到。

进一步观察,我发现迭代器(至少对于字符串)有一个公共(public)的 _GetCont() 方法。所以

if ( iter1._GetCont() == iter2._GetCont() )

有效。但是,这是没有记录的,这让我相信它使用起来不安全。

我的问题是如何以可移植的方式完成上述操作?

还要注意,这是迭代器模板类的一部分。我将无法控制第二个迭代器。

最佳答案

My question is how can I accomplish the above in a portable manner?

你不能。

一般来说,迭代器不需要知道(或让知道)它们指向的容器。迭代器是指针的概括,它们所需要做的就是表现得像指针。

因此它们可能允许取消引用、递增、递减、求和等,具体取决于它们的类别,但 C++ 标准中没有迭代器要求让用户知道它们指向哪个容器,或者它们是否指向与另一个迭代器相同的容器。

换句话说,迭代器范围的有效性应该是作用于该迭代器范围的函数的前提。客户端有责任确保提供的迭代器指向同一个容器(并且第二个迭代器可以从第一个迭代器访问)。

例如,标准库是如何处理这个问题的(C++11 标准第 24.2.1/7 段):

Most of the library’s algorithmic templates that operate on data structures have interfaces that use ranges. A range is a pair of iterators that designate the beginning and end of the computation. A range [i,i) is an empty range; in general, a range [i,j) refers to the elements in the data structure starting with the element pointed to by i and up to but not including the element pointed to by j. Range [i,j) is valid if and only if j is reachable from i. The result of the application of functions in the library to invalid ranges is undefined.

关于c++ - 测试两个迭代器是否来自同一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17492160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com