就个人而言,我认为混合递归和对象有点奇怪。对象的基本概念之一是对象保持您想要跟踪的状态。递归的基本概念之一是执行堆栈保存您想要跟踪的状态。
在这种情况下,您要跟踪的状态是已处理了多少字符串/还有多少字符串需要处理。您可以在没有对象的情况下跟踪它。
这闻起来很像家庭作业问题。但是我想不出一个提示给你而不只是给你答案。我能做的最好的就是让我的答案(1)反转任何容器,包括但不限于字符串;(2) 使用类似 STL 的接口(即迭代器);(3) 将字符串反转到位,而不是反转字符串的副本:
#include <algorithm> // std::swap
// the other headers are only for my example on how to use the code
#include <iostream>
#include <iterator>
#include <string>
#include <list>
template<typename Itor> void reverse_with_recursion(Itor begin, Itor end)
{
using std::swap; // same trick used by the STL to get user-defined swap's,
// but fall back to std::swap if nothing else exists:
// http://en.wikipedia.org/wiki/Argument-dependent_name_lookup#Interfaces
// if begin and end are pointing at the same element,
// then we have an empty string and we're done
if (begin == end) {
return;
}
// the STL follows the pattern that end is one element after
// the last element; right now we want the last element
--end;
// if begin and end are pointing at the same element *now*,
// then we have a single character string and we're done
if (begin == end) {
return;
}
swap(*begin, *end);
return reverse_with_recursion(++begin, end);
}
int main()
{
std::string foo("hello world");
reverse_with_recursion(foo.begin(), foo.end());
std::cout << foo << '\n';
std::list<int> bar;
for (int i = 0; i < 10; ++i) {
bar.push_back(i);
}
reverse_with_recursion(bar.begin(), bar.end());
std::copy(bar.begin(),
bar.end(),
std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';