我有一个小问题。我想利用字符串中的双字母。我设法编译了一个程序,但是没有成功。
#include <iostream>
#include <cctype>
#include <string>
std::string::iterator function(
std::string::const_iterator a,
std::string::const_iterator b,
std::string::const_iterator e)
{
for (; a < b; a++)
{
if (*a == *(a + 1))
{
toupper(*a);
toupper(*(a + 1));
}
}
}
int main()
{
std::string in = "peppermint 1001 bubbles balloon gum", out(100, '*');
auto e = function(in.cbegin(), in.cend(), out.begin());
int n = e - out.begin();
std::string s = out.substr(0, n);
bool b = (s == "pePPermint 1001 buBBles baLLOOn gum");
std::cout << std::boolalpha << b << std::endl;
}
我做错了什么?
那里有几个问题。
首先,您的函数答应返回 std::string::iterator
std::string::iterator function(....)
{
//... return statement is missing here!
}
并且您没有遵守诺言。这将导致不确定的行为。例如,在您的情况下,它只是编译而没有给出输出。
为了获得定义的行为,您应该从函数返回
std::string::iterator function(...)
{
// ... code
return {}; // return appropriately iterator of std::string
}
其次,您要修改字符串的字符,这需要可修改的迭代器而不是std::string::const_iterator
。
然后在循环中,您需要char
通过重新分配大写字母来改变它。例如:
*a = toupper(*a);
第三,您应该谨慎地在函数的for循环中执行此操作
for(; a < b; a++)
{
if(*a == *(a + 1)) // --->here
// ... code
}
当a== str.end()-1
,您仍然会进行增量操作(即*(a + 1)
),会发生什么情况?再次增加结束迭代器会导致您出现未定义的行为。
在这种情况下,您可以使用std::next
from<iterator>
标头安全地进行检查。
以下是演示代码,清除了上述问题:
#include <iostream>
#include <string>
#include <iterator> // std::next
std::string::iterator function(
std::string::iterator a,
std::string::iterator b,
std::string::iterator e)
{
auto beg = a;
for (; a < b; a++)
{
if (std::next(a) != b && *a == *std::next(a)) {
*a = toupper(*a);
*std::next(a) = toupper(*std::next(a));
}
}
std::cout << std::string{ beg, b };
return {}; // return appropriately iterator of std::string
}
现在打印:https : //godbolt.org/z/ZsLHxw
pePPermint 1001 buBBles baLLOOn gum
我假设您想以某种方式将输出传递给第三个功能参数std::string::iterator e
。我会让那部分让您解决。同时,请查看标准算法功能std::transform
,这可能对进行此类转换很方便。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句