使用 std::string 迭代器查找字符串的开头和结尾

发布于 2024-08-23 17:56:05 字数 130 浏览 9 评论 0原文

仅给定一个 std::string 迭代器,是否可以确定字符串的起点和终点?假设我无权访问字符串对象,因此无法调用 string.begin() 和 string.end(),我所能做的就是递增或递减迭代器并测试值。

谢谢, 菲尔

Given just a std::string iterator, is it possible to determine the start and end points of the string? Supposing that I don't have access to the string object and so cannot call string.begin() and string.end(), and all I can do is increment or decrement the iterator and test the value.

Thanks,
Phil

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

原来是傀儡 2024-08-30 17:56:05

简短的回答是否定的。长答案是,因为迭代器不希望知道正在迭代的容器或范围,所以它们只希望能够

  • 跳转到下一个元素(inc或dec到下一个或上一个)
  • 取消引用自身以便揭示对它们所指向的值的引用
  • 当然,将它们与其他迭代器进行比较,最重要的是某种“结束”迭代器。

此外,某些类型的迭代器可能不仅仅执行上述操作,但原则上它们都需要以某种形式具有/执行上述操作。

The short answer is no. The long answer is, because iterators aren't expected to know about the containers or ranges that are iterating over, they are only expected to

  • Be able to jump to the next element (inc or dec to next or prev)
  • Dereference themselves so as to reveal a reference to the value they are pointing to
  • And over course compare themselves with other iterators most importantly an "end" iterator of some kind.

Furthermore certain types iterators may do more than just the above, but principally they are all required to have/perform the above in some form or another.

温柔女人霸气范 2024-08-30 17:56:05
  • 对于字符串的结束点:
    假设内部字符串以空字符结尾。然后通过解引用迭代器来查看它们是否为'\0'来确定下一个位置是终点。但对于其他非空终止字符串,不可能了解此类信息。
  • 对于字符串的起点:
    没办法做这种事。

默认的 std::string::iterator 只是一个随机的双向迭代器,对容器一无所知。

但是如果你在 Visual C++ 平台上工作,也许你可以使用一些像下面这样的黑客方法来获取对其容器的控制,但这是非常危险的:

  // it is the passed in string::iterator parameter.
  if (it._Has_container()) {
      string* strRef = (string*)it._Mycont;
  }
  • For the end point of the string:
    Assume the internal character string is null-terminated. Then through dereferencing the iterator to see if they're '\0' to determine the next position is end point. But for other non null-terminated string, it's impossible to get to know such information.
  • For the start point of the string:
    No way to do such thing.

The default std::string::iterator is just a random, bi-direction iterator, doesn't know anything about container.

But if you're working on Visual C++ platform, maybe you can use some hacking way like following to get the control to its container, but it's very dangerous:

  // it is the passed in string::iterator parameter.
  if (it._Has_container()) {
      string* strRef = (string*)it._Mycont;
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文