c++ - 如何检查 std::next(x) 是否指向 C++ 中的有效地址?

标签 c++ c++11 vector iterator runtime-error

假设我有以下填充数据的 std::string vector :

std::vector<std::string> japan;

然后,我按如下方式在 vector 中搜索元素:

std::string where;

auto found = std::find(japan.begin(), japan.end(), where);

我的问题是,有时我需要根据“找到的”元素检查 vector 中的下一个元素,如下所示:

std::string here = *std::next(found);

但是,下一个迭代器并不总是有东西,尝试访问这种不存在的元素会给我“表达式: vector 迭代器不可取消引用”运行时错误消息,这是可以理解的。

我的问题是,如何检查 std::next(found) 是否是有效地址,这样我就不会引发上述错误?

最佳答案

不可能只用它自己来检查单个迭代器的有效性,它不包含必要的信息。您将需要容器的帮助。例如

auto found = std::find(japan.begin(), japan.end(), where);
if (found != japan.end()) {
    // if found is valid
    auto next = std::next(found);
    if (next != japan.end()) {
        // if next is valid
        std::string here = *next;
    }
}

关于c++ - 如何检查 std::next(x) 是否指向 C++ 中的有效地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47986566/

相关文章:

c++ - 从已知大小的 double 组构造 std::vector<double>

android - Vector Drawables 与 RAM 方面的位图 (Android)

c++ - 错误 :sorry, 未实现:在函数模板中使用 decltype 时,函数模板签名中存在字符串文字

C++ 在 try block 中创建对象,然后将它们存储在 std::array 中

c++ - 如何使用模板处理不同维度的矩阵?

Java - Vector 与 ArrayList 性能 - 测试

python - Python 中确定矩阵中所有可能交点的最佳方法?

c++ - 带有 boost::asio::read 的 EOF

c++ - 无法将 MyClass* 转换为 const MyClass

c++ - 我们是否需要删除对非新对象的引用?