C++ 避免在不强制转换的情况下混合索引和指针算法时使用C4365
我有一个代码库,模板在一个向量中查找一个值,然后使用计算出的索引在某个位置获得一个值 下面是一些为visual studio制作的源代码,提供了一个大致的概念:C++ 避免在不强制转换的情况下混合索引和指针算法时使用C4365,c++,visual-studio,compiler-warnings,C++,Visual Studio,Compiler Warnings,我有一个代码库,模板在一个向量中查找一个值,然后使用计算出的索引在某个位置获得一个值 下面是一些为visual studio制作的源代码,提供了一个大致的概念: #pragma once #pragma warning(disable: 4514) #pragma warning(disable: 4710) #pragma warning(disable: 4189) #include <vector> int main(int, char *[]) { //contr
#pragma once
#pragma warning(disable: 4514)
#pragma warning(disable: 4710)
#pragma warning(disable: 4189)
#include <vector>
int main(int, char *[])
{
//contrived example, never mind the non C4365 issues in this code
//I am aware that this makes not a lot of sense runtime wise
//This question is about a compiler warning
int target;
std::vector<char> first;
std::vector<long> second;
auto it = std::find(first.begin(), first.end(), target);
//Warning C4365 '...': conversion from '...' to '...', signed/unsigned mismatch
std::size_t pos = it - first.begin(); //from int to std::size_t
long result = second.at(pos);
return 0;
}
#pragma一次
#杂注警告(禁用:4514)
#杂注警告(禁用:4710)
#杂注警告(禁用:4189)
#包括
int main(int,char*[])
{
//人为的例子,不要在意代码中的非C4365问题
//我知道这在运行时没有多大意义
//此问题与编译器警告有关
int目标;
std::向量优先;
std::向量秒;
auto it=std::find(first.begin()、first.end()、target);
//警告C4365“…”:从“…”转换为“…”,有符号/无符号不匹配
std::size\u t pos=it-first.begin();//从int到std::size\u t
长结果=第二个点(位置);
返回0;
}
我对C4365特别感兴趣。
有一个条目,还有一个与此相关的问题
我知道这是std::size\u t pos=static\u cast(it-first.begin())代码>删除警告
我的问题是,是否可以编写上面的查找和获取值,以便不需要强制转换来避免警告
编辑:我没有提到此警告在默认情况下处于警告级别4和关闭状态。下面的代码不会生成警告,因为您将向迭代器添加一个
int
,这是有效的
int main(int, char *[])
{
//contrived example, never mind the non C4365 issues in this code
//I am aware that this makes not a lot of sense runtime wise
//This question is about a compiler warning
int target;
std::vector<char> first;
std::vector<long> second;
auto it = std::find(first.begin(), first.end(), target);
auto it2 = second.begin() + ( it - first.begin() );
long result = *it2;
return 0;
}
intmain(int,char*[])
{
//人为的例子,不要在意代码中的非C4365问题
//我知道这在运行时没有多大意义
//此问题与编译器警告有关
int目标;
std::向量优先;
std::向量秒;
auto it=std::find(first.begin()、first.end()、target);
auto it2=second.begin()+(it-first.begin());
长期结果=*it2;
返回0;
}
auto pos=it-first.begin()代码>?@NathanOliver在本例中,类型将是int,这将把警告移动到下一行,在该行中需要一个未签名的。它会吗?“在我的机器上没有。”纳萨诺利夫说,“很有趣。你确定你打开了墙吗?好了。我忘了提高警戒级别。我在/W3上。