是否有用于C字符串的标准C ++迭代器? [英] Is there a standard C++ iterator for C strings?
问题描述
有时我需要使用通用的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 ++迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!