gpt4 book ai didi

c++ - 无法递归创建 C++ 数组

转载 作者:行者123 更新时间:2023-12-01 12:45:07 28 4
gpt4 key购买 nike

我想测试一个递归方法,下面的代码有一个编译错误。我已经仔细检查了下标变量,它们应该是正确的。我真的想不通,有人可以帮我吗?

#include <iostream>
#include <array>
using namespace std;

template <typename T, size_t Size>
void fn(array<T, Size>& data) {
const size_t begin{0};
const size_t end{Size-1};
const size_t leftUpper{(begin+end)/2};
const size_t rightLower{leftUpper+1};

if (data.size() > 1 ) {
array<T, end+1-rightLower> right;
cout << "Right: " << end+1-rightLower << endl;
fn(right);
}
}

int main() {
array<int, 5> test;
fn(test);
}

编译错误是:
$ g++ -std=c++14 GuessNumber.cpp -o test
In file included from GuessNumber.cpp:2:0:
/usr/lib/gcc/x86_64-pc-cygwin/7.3.0/include/c++/array: In instantiation of ‘struct std::array<int, 2305843009213693952>’:
GuessNumber.cpp:15:9: recursively required from ‘void fn(std::array<_Tp, _Nm>&) [with T = int; long unsigned int Size = 2]’
GuessNumber.cpp:15:9: required from ‘void fn(std::array<_Tp, _Nm>&) [with T = int; long unsigned int Size = 5]’
GuessNumber.cpp:21:11: required from here
/usr/lib/gcc/x86_64-pc-cygwin/7.3.0/include/c++/array:94:12: error: size of type ‘std::array<int, 2305843009213693952>’ is too large (‘9223372036854775808’ bytes)
struct array
^~~~~

最佳答案

尝试这个:

#include <iostream>
#include <array>
using namespace std;

// the function contains its body just because looks like
// you want to implement some other logic there
template <typename T>
void fn(array<T, 2ul>& data) {
const size_t Size = 2;
const size_t begin{0};
const size_t end{Size-1};
const size_t leftUpper{(begin+end)/2};
const size_t rightLower{leftUpper+1};
array<T, end+1-rightLower> right;
cout << "Right: " << end+1-rightLower << endl;
}

template <typename T>
void fn(array<T, 1ul>& data) {
}

template <typename T>
void fn(array<T, 1ul>& data) {
const size_t Size = 1;
const size_t begin{0};
const size_t end{Size-1};
const size_t leftUpper{(begin+end)/2};
const size_t rightLower{leftUpper+1};
array<T, end+1-rightLower> right;
cout << "Right: " << end+1-rightLower << endl;
}

template <typename T, size_t Size>
void fn(array<T, Size>& data) {
const size_t begin{0};
const size_t end{Size-1};
const size_t leftUpper{(begin+end)/2};
const size_t rightLower{leftUpper+1};

if (data.size() > 1 ) {
array<T, end+1-rightLower> right;
cout << "Right: " << end+1-rightLower << endl;
fn(right);
}
}

int main() {
array<int, 5> test;
fn(test);
}

您的代码不是有条件地编译的。 if当您执行模板魔术时,s 不会像您期望的那样工作。另一个例子是 here

关于c++ - 无法递归创建 C++ 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61906404/

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