请帮助 C++ 新手理解这里出了什么问题。我收到编译错误消息 Non-constant-expression cannot be narrowed from type 'unsigned long' to 'int' in initializer list
在 leetcode web 和我本地的 ubuntu 终端上,但它在我的 CLion IDE 上运行得很好。还可以解释为什么我收到错误以及如何解决它?
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<vector<int>> heights({{1, 2, 2, 3, 5}, {3, 2, 3, 4, 4}, {2, 4, 5, 3, 1}, {6, 7, 1, 4, 5}, {5, 1, 1, 2, 4}});
deque<vector<int>> dq;
for (int i=0;i<heights.size();i++){
dq.push_back({i,heights[0].size()-1});
}
for (auto vec: dq){
if (vec.empty())
cout<< "vec is empty";
else
cout<<vec[0]<< " "<< vec[1]<<endl;
}
return 0;
}
一旦切换到pair
来自vector<int>
,错误消失了。对于我这样的新手来说,这是相当困惑的。请阐明这一点。
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<vector<int>> heights({{1, 2, 2, 3, 5}, {3, 2, 3, 4, 4}, {2, 4, 5, 3, 1}, {6, 7, 1, 4, 5}, {5, 1, 1, 2, 4}});
deque<pair<int, int>> dq;
for (int i=0;i<heights.size();i++){
dq.push_back({i,heights[0].size()-1});
}
for (auto [u,v]: dq){
cout<<u<< " "<< v<<endl;
}
return 0;
}
最佳答案
当您使用大括号初始化时,禁止使用缩小转换来从大括号列表中的值类型转换为构造函数实际需要的类型。 heights[0].size()-1
类型为size_t
,以及 std::vector<int>
的构造函数需要std::initializer_list<int>
。通常,int
无法表示 size_t
类型的所有值,这意味着size_t
至int
是一个缩小转换。您可以使用显式强制转换来解决此问题:
dq.push_back({i,static_cast<int>(heights[0].size()-1)});
当正在构造的类型为 std::pair<int, int>
时,这是一个不同的故事。调用构造函数时实际上不会发生任何转换;相反,调用以下构造函数:
template< class U1, class U2 >
constexpr pair( U1&& x, U2&& y );
参见cppreference .
在内部,大概在构造函数初始值设定项列表中,构造函数将转换 size_t
至int
,但这不会在大括号内完成,所以它是合法的。
关于c++ - 初始化列表中的非常量表达式无法从类型 'unsigned long' 缩小到 'int',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70615011/