C++字符串的迭代器问题
Iterator woes with C++ strings
对于赋值,我们必须执行一个以各种方式操纵C++字符串的大型程序。它的大部分功能都在起作用,但这个特定的功能让我很困惑。我试图在第一个字母数字字符出现之前循环遍历一个字符串并删除所有非字母数字字符(制表符、空白换行符),然后在第一个非字母数字字符再次出现时结束字符串。例如,"bob-jon"将被保存为"bob"。在每个字符串都被认为是空的地方出现了问题。大多数同行都认为
*(point++) = *marker;
做不到,我应该在尝试其他事情之前改变这个。。。这是一种在将迭代器的值分配给另一个迭代器值的同时增加迭代器数量的方法吗?是这个问题还是别的什么?
void clean_entry( const string& j, string& k )
{
string::iterator point = k.begin();
bool checker = false;
//cycle through the constant string and check for numbers and letters
for(string::const_iterator marker = j.cbegin(); marker!=j.cend(); ++marker)
{
if( isalnum(*marker) == true )
{
*(point++) = *marker; //copy to the new k string if alphanum, and increment iterator
cout << "I found a real letter!" << endl; //debugging
checker = true;
}
else if( checker == true )
break;
}
cout << "So far we have " << k << endl; //debugging
if (checker == false )
k = "(empty word)";
cout << "The new string is " << k << " apparently." << endl; //debugging
}
isalnum
不返回bool
。返回int
。保证是,如果字符是字母数字,则返回非零,否则返回零。这意味着您无法将返回值与true
进行比较,因为在进行比较之前,该比较会导致true
转换为int
,从而生成1
。。if(isalnum(*marker))
既是惯用语,也是实际有效的类似地,
if( checker == true )
是膨胀的并且应该是if(checker)
,并且if (checker == false )
应该是if(!checker)
- 您的接口是有问题的,因为调用者必须确保
k
的大小足够大,以容纳生成的字符串。最好清除k
,然后使用push_back()
或类似程序,而不是迭代器
假设k.size()
足够大,那么*(point++) = *marker;
没有什么问题。
相关文章:
- ESP8266单片机矢量迭代器的C++问题
- 成员函数中的迭代器出现问题
- 迭代器的指针操作问题
- 为什么在这个C++问题中使用const_iterator而不仅仅是迭代器?
- std::filesystem::directory_迭代器链接器问题(C++17)
- 使用 find() 通过 std::set 的迭代器将不起作用。出了什么问题?
- 无法取消引用超出范围的向量迭代器 - 有什么问题?
- 调用模板函数的问题"No matching function for call"参数:迭代器、对象函数
- 迭代器的问题
- 无法理解迭代器的问题?
- 使用迭代器时遇到问题,每 M 次传递一次擦除一个向量项
- 有关使用矢量迭代器访问对象方法的问题
- 自定义迭代器而不是解释问题
- 基于范围的自定义迭代器:constness问题
- 常量迭代器的问题
- 对于循环迭代器问题 c++
- 如果使用迭代器,如何解决遍历列表的问题
- 字符串迭代器不可用C 问题
- 将MAP与一对用作C 迭代器问题中的键
- 我的自定义迭代器有什么问题