是否有用于C字符串的标准C ++迭代器?

编程入门 行业动态 更新时间:2024-10-11 07:25:50
本文介绍了是否有用于C字符串的标准C ++迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有时我需要使用通用的C ++迭代器范围接口[first, last)将C字符串传递给函数.在这些情况下,是否有标准的C ++迭代器类,或者不需要复制字符串或调用strlen()的标准方式?

我知道我可以将指针用作迭代器,但我必须知道字符串的结尾,什么使我需要调用strlen().

虽然我不知道这样的迭代器是否标准化,但我当然知道是可能的.回应讽刺的答案和评论,这是存根(不完整,未经测试):

class CStringIterator { public: CStringIterator(char *str=nullptr): ptr(str) {} bool operator==(const CStringIterator& other) const { if(other.ptr) { return ptr == other.ptr; } else { return !*ptr; } } /* ... operator++ and other iterator stuff */ private: char *ptr; };

具体来说,我对转发迭代器感兴趣,因为我想避免进行迭代我知道算法只需要做一次就可以了.

解决方案

恐怕不是,最后,您将需要一个指向要调用strlen的字符串末尾的指针. /p>

Sometimes I need to pass a C string to a function using the common C++ iterator range interface [first, last). Is there a standard C++ iterator class for those cases, or a standard way of doing it without having to copy the string or call strlen()?

EDIT: I know I can use a pointer as an iterator, but I would have to know where the string ends, what would require me to call strlen().

EDIT2: While I didn't know if such iterator is standardized, I certainly know it is possible. Responding to the sarcastic answers and comments, this is the stub (incomplete, untested):

class CStringIterator { public: CStringIterator(char *str=nullptr): ptr(str) {} bool operator==(const CStringIterator& other) const { if(other.ptr) { return ptr == other.ptr; } else { return !*ptr; } } /* ... operator++ and other iterator stuff */ private: char *ptr; };

EDIT3: Specifically, I am interested in a forward iterator, because I want to avoid to iterate over the sring twice, when I know the algorithm will only have to do it once.

解决方案

I'm afraid not, for last you'll need a pointer to the end of the string for which you'll need to call strlen.

更多推荐

是否有用于C字符串的标准C ++迭代器?

本文发布于:2023-11-22 01:37:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615467.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   迭代   标准

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!