[英]Error in ternary operator, thowing error: “expected primary-expression before ';' token ”
[英]Primary expression error when defining a vector with ternary operator
我有一個簡單的代碼,我嘗試使用三元運算符將向量定義為兩個初始值設定項列表之一:
int main() {
std::vector<int> const vec = true ? {3,4} : {5};
for (int const item : vec) {
cout << item << endl;
}
return 0;
}
但后來我看到以下主要表達式錯誤:
tmp.cpp: In function ‘int main()’:
tmp.cpp:7:41: error: expected primary-expression before ‘{’ token
std::vector<int> const vec = true ? {3,4} : {5};
^
tmp.cpp:7:41: error: expected ‘:’ before ‘{’ token
tmp.cpp:7:41: error: expected primary-expression before ‘{’ token
tmp.cpp:7:47: error: expected ‘,’ or ‘;’ before ‘:’ token
std::vector<int> const vec = true ? {3,4} : {5};
我在三元運算符或初始化程序列表初始化中找不到任何相關內容。 我在這里想念什么?
因為在那種情況下你不能有大括號。 如果您查看 列表初始化上的 cppreference ,您會發現三元運算符中的大小寫沒有定義。 所以它不能被正確解析,你會得到你所遇到的錯誤。
你必須使用這樣的東西:
std::vector<int> const vec{(true ? std::vector<int>{3, 4} : std::vector<int>{5})};
基本上擴展為:
if (true) {
vec = std::vector<int>{3, 4};
} else {
vec = std::vector<int> { 5 }
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.