gpt4 book ai didi

C++:使用迭代器替换部分字符串不起作用

转载 作者:行者123 更新时间:2023-11-27 22:32:03 24 4
gpt4 key购买 nike

我正在编写一个简单的程序,它试图在给定数字之后找到下一个回文数字。

至于现在,我卡在了这一点上:

string::iterator iter; // iterators for the string
string::iterator riter;


//testcases is a vector<string> with strings representing numbers.
for (unsigned int i = 0; i < testcases.size() ; ++i) {
iter = testcases[i].begin();
riter = testcases[i].end();

while ( !isPalin(testcases[i]) ) { //isPalin(string) is a function
//which is checking if given string
//is a palindrome

//if n-th digit from the end is different from the
//n-th digit, then I want to replace latter one, so they will
//be the same.
if ( *iter != *riter ) {
testcases[i].replace(riter, riter, *iter);
}

++iter; // advancing forward iterator;
--riter; // advancing backward iterator;
}
cout << testcases[i] << " -> ok\n";
}

当我使用 Microsoft Visual Studio 2008 编译这个时,出现了这个错误:

Compiling...
main.cpp
.\main.cpp(53) : error C2664: 'std::basic_string<_Elem,_Traits,_Ax> &std::basic_string<_Elem,_Traits,_Ax>::replace(unsigned int,unsigned int,const std::basic_string<_Elem,_Traits,_Ax> &)' : cannot convert parameter 1 from 'std::_String_iterator<_Elem,_Traits,_Alloc>' to 'unsigned int'
with
[
_Elem=char,
_Traits=std::char_traits,
_Ax=std::allocator
]
and
[
_Elem=char,
_Traits=std::char_traits,
_Alloc=std::allocator
]
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

我是在做傻事还是漏掉了什么?如果有任何帮助/建议,我将不胜感激。

最佳答案

关于您拥有的代码:

为什么不直接在两个迭代器的末尾赋值?

if ( *iter != *riter ) {
*riter = *iter;
}

正如 Oli 所指出的,代码中还有其他问题,第一个问题是您将 riter 设置为 string.end(),这是一个不可取消引用的迭代器。 end() 迭代器始终是最后一个,因此上面的使用将尝试写入超出分配的内存。

也许您应该尝试使用 .rbegin() 代替。它将提供一个反向迭代器,指向在您递增字符串时移向字符串开头的最后一个元素。

关于算法:

如果您的意图是找到下一个回文数字,我不确定您实现的算法是否正确。例如,如果输入数字是 123456,算法将检测到它不是回文,并将转换为小于原始数字的 12345_1_。

关于C++:使用迭代器替换部分字符串不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1096207/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com