gpt4 book ai didi

c++ - 尾递归可以应用于此代码吗?

转载 作者:行者123 更新时间:2023-11-28 00:21:02 25 4
gpt4 key购买 nike

我有一段简单的代码,地址是 this (表述不当,不合适)问题:

template<typename It>
bool isAlpha(It first, It last)
{
return (first != last && *first != '\0') ?
(isalpha(static_cast<int>(*first)) && isAlpha(++first, last)) : true;
}

我正在尝试找出如何以尾递归方式 实现它,尽管有像这样的重要资源 answer ,我无法全神贯注。

有人可以帮忙吗?

编辑

我把反汇编代码放在下面;编译器是 gcc 4.9.0 使用 -std=c++11 -O2 -Wall -pedantic 编译,汇编输出是

bool isAlpha<char const*>(char const*, char const*):
cmpq %rdi, %rsi
je .L5
movzbl (%rdi), %edx
movl $1, %eax
testb %dl, %dl
je .L12
pushq %rbp
pushq %rbx
leaq 1(%rdi), %rbx
movq %rsi, %rbp
subq $8, %rsp
.L3:
movsbl %dl, %edi
call isalpha
testl %eax, %eax
jne .L14
xorl %eax, %eax
.L2:
addq $8, %rsp
popq %rbx
popq %rbp
.L12:
rep ret
.L14:
cmpq %rbp, %rbx
je .L7
addq $1, %rbx
movzbl -1(%rbx), %edx
testb %dl, %dl
jne .L3
.L7:
movl $1, %eax
jmp .L2
.L5:
movl $1, %eax
ret

最佳答案

为了澄清 cdhowie 的观点,该函数可以重写如下(除非我弄错了):

bool isAlpha(It first, It last)
{
if (first == last)
return true;
if (*first == '\0')
return true;
if (!isalpha(static_cast<int>(*first))
return false;
return isAlpha(++first, last);
}

这确实可以消除琐碎的尾调用。

不过,这通常是编译器的工作。

关于c++ - 尾递归可以应用于此代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27464462/

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