编译器错误 C4244:'initializing':从 '__int64' 转换为"int",可能会丢失数据
Compiler error C4244: 'initializing' : conversion from '__int64' to 'int', possible loss of data
我正试图使用std::count而不是std::vector,如下所示:
int count = std::count( stdVector.begin(), stdVector.end(), "element" );
在windows上,它会给出以下编译器错误。
error C4244: 'initializing' : conversion from '__int64' to 'int', possible loss of data
如果我按照以下方式更改代码,Windows
编译器不会出现。
auto count = std::count( stdVector.begin(), stdVector.end(), "element" );
然而,由于上述更改,现在我在linux上面临以下错误。
error: ISO C++ forbids declaration of 'count' with no type
我该如何使用std::count
,它将在两个平台上构建而不会出现任何错误?
在不同的环境中,有两件事可能会发生不同的冲突:
第一个是auto
,作为一个推导类型是C++11的特征。可能是linux编译器没有默认值(只需使用-std=c++11
,如果没有,请升级!)
另一种是std::count的返回类型是size_t
,而不是int
,并且size_t
到int
的转换可能会丢失数据,这取决于size_t
的定义方式(至少存在有符号/无符号不匹配,并且最终两种类型的大小不同,如int
的32位和size_t
的64位)。
收到此警告的原因是,在64位构建中,标准容器使用64位值作为大小类型,而将64位值(例如size_t
)隐式转换为32位值(如int
)可能会丢失数据。
如果编译器不支持auto
,那么count
函数返回的实际数据类型(在本例中为std::vector<T>::difference_type
)可能是最好的类型。使用size_t
可能也会在没有警告的情况下工作,并且键入时间要短得多。
或者,如果您不担心数据丢失的风险(例如,从未计划在容器中有超过2^32-1个对象),您可以简单地放弃警告:
int count = static_cast<int>( std::count(stdVector.begin(), stdVector.end(), "element") );
- 如何计算数据类型的范围,例如int
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 如何将 std::vector 索引交换到<int>数据,将数据交换到索引
- 错误:请求"数据"中的成员"大小",其非类类型为"int [5]"
- 从带有 std::ifstream::read() 的文件中读取 int 遍历 char * 二进制数据
- 有没有办法"QByteArray"变量数据直接放入变量"int"而无需强制转换?
- 利用输入文件中的数据(字符串和int)并在循环中利用
- 引用数据的 int 指针
- unordered_set是否适合存储矢量<int>元素的数据结构?如果是这样,我将如何实现哈希函数?
- 如何对 int 变量应用验证,使其仅接受整数数据,并且在任何其他数据的情况下不会出错?
- 如何将来自文本文件的数据读取到结构的int阵列中
- 什么是在C 中存储结果INT*的最佳数据类型
- 返回int数据类型v/s传递参考
- 如何让我的构造函数和函数工作,以便我的 main() 能够同时显示字符串和 int 数据
- 如何掩盖对象数组的数据类型字符串到C 中的INT
- 如何将JSON文件中的数据转换为值(double,int ..)
- 将数据从文件读取到单独的int值
- 预安装库中的常见数据类型(Int、Char 等)大写
- 如何在 c++ 中将数据从文件读取到 int/float 值
- 从 T 转换为无符号 int,可能会丢失数据