无法将"notes"从"std::array<double, 6u>"转换为"std::array<double, 7u>

Could not convert 'notes' from 'std::array<double, 6u>' to 'std::array<double, 7u>

本文关键字:gt double lt array std 7u 6u 转换 notes      更新时间:2023-10-16

我有一个与push_back()相同的函数,但它不起作用。

我该如何解决这个问题?

#include <iostream>
#include <array>
#include <string>
using namespace std;
double add(array<double, 6> const& tab);
void add_push_back(array<double, 6+1> tab);
int main()
{
    const int tailleTab{6};
    array<double, tailleTab> notes = { 11.0, 9.5, 8.4, 12.0, 14.01, 12.03 };
    double myMoyenne{};
    myMoyenne = add(notes);
    cout << myMoyenne;
    add_push_back(notes);
    for (auto note: notes){
        cout << note << endl;
    }
    return 0;
}
double add(array<double, 6> const& tab){
    double result{};
    for (double note: tab){
        result += note;
    }
    result /= tab.size();
    return result;
}
void add_push_back(array<double, 6+1> tab){
    array<double, 6+1> push;
    for (unsigned int i = 0; i < tab.size(); ++i){
        push.at(i) += tab.at(i);
    }
    push.at(7) = {7};
    for (unsigned int i = 0; i < push.size(); ++i){
        tab.at(i) += push.at(i);
    }
}

错误:

error: could not convert 'notes' from 'std::array<double, 6u>' to 'std::array<double, 7u>'|

您不能将包含6个元素的std::array传递到一个函数中,该函数期望std::array包含7个元素,因为std::array<type, 6>是与std::array<type, 7>不同的类型。具有不同模板参数的模板类被编译器认为是不同的类型。

要解决眼前的问题,需要将add_push_backtab参数从array<double, 6+1>更改为array<double, 6>

但是,我建议您使用更适合调整大小的std::vectorstd::deque。快速查看代码表明,您甚至无法对数组执行您想要执行的操作。您不能在运行时动态调整std::array的大小。

您的数组大小不匹配。notes数组有6个元素,而预期有7个元素。参见add_push_back的签名,参数为array<double, 6+1>