![](/img/trans.png)
[英]Assign C array to C++'s std::array? (std::array<T,U> = T[U]) - no suitable constructor exists from "T [U]" to "std::array<T,U>"
[英]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_back
的tab
參數從array<double, 6+1>
更改為array<double, 6>
。
但是 ,我建議您使用更適合調整大小的std::vector
或std::deque
。 快速查看您的代碼表明您甚至無法使用數組進行嘗試。 您不能在運行時動態調整std::array
大小。
您的數組大小不匹配。 notes
數組包含6個元素,而預期為7個。 請參見add_push_back
的簽名,參數為array<double, 6+1>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.