可能重复:
C++检查迭代器是否有效的最佳方法
我想做这样的事情:
std::vector<int>::iterator it;
// /cut/ search for something in vector and point iterator at it.
if(!it) //check whether found
do_something();
Run Code Online (Sandbox Code Playgroud)
但是没有运营商!用于迭代器.如何检查迭代器是否指向任何东西?
我一直认为"奇异"迭代器是一个默认初始化的迭代器,它们可以作为类似的哨兵值:
typedef std::vector<Elem>::iterator I;
I start = I();
std::vector<Elem> container = foo();
for (I it = container.begin(), end = container.end(); it != end; ++it) {
if ((start == I()) && bar(it)) {
// Does something only the first time bar(it) is satisfied
// ...
start = it;
}
}
Run Code Online (Sandbox Code Playgroud)
但这个答案不仅表明我对"单数"的定义是错误的,而且我上面的比较完全是非法的.
是吗?
考虑这段代码:
#include <iostream>
#include <string>
#include <map>
int main()
{
std::map<std::string, std::string> map = {
{ "ghasem", "another" }
};
std::cout << map.find("another")->second << std::endl;
std::cout << map.size() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
它将被编译并成功运行(进程返回值为0),但我们看不到 的输出map.size()。既-fsanitize=address没有-fsanitize=undfined报告任何问题。我用GCC-11.2.1和Clang-13.0.0编译,两者是一样的。使用 GDB-11.1-5 逐步运行代码不会有帮助,所有步骤都会成功运行。
但如果我重新排序最后两行:
#include <iostream>
#include <string>
#include <map>
int main()
{
std::map<std::string, std::string> map = {
{ "ghasem", "another" }
};
std::cout << map.size() << std::endl;
std::cout << map.find("another")->second << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
我将收到分段错误,现在 ASAN 可以报告该错误。
我的问题是:代码是否会导致某种未定义的行为?我怎样才能检测到这些错误?
可能重复:
C++检查迭代器是否有效的最佳方法
假设我有一个函数,它将迭代器作为唯一参数,如下所示.
void DoSomethingWithIterator(std::vector<int>::iterator iter)
{
// Check the pre-condition
assert( /* how to validate iter here? */ )
// Operate on iter afterwards
..
}
Run Code Online (Sandbox Code Playgroud)
我怎么知道是否iter有效.通过有效的,我的意思是它指向的载体,例如,从内部的现有元素m_intVector.begin()来m_intVector.end().