簡體   English   中英

無法從&#39;std :: array轉換&#39;notes&#39; <double, 6u> &#39;至&#39;std :: array <double, 7u>

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

我有一個與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傳遞給期望包含7個元素的std::array的函數,因為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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM