在不强制转换的情况下混合索引和指针算法时避免 C4365

Avoiding C4365 when mixing index and pointer arithmetic without casting

我有一个代码库,模板在其中查找一个向量中的值,然后使用计算出的索引在特定位置获取值。

这里有一些为 visual studio 制作的源代码,可以给出一个大概的概念:

#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;
}

我对警告 C4365 特别感兴趣。 MSDN has an entry and there is another Whosebug 与此相关的问题。

我了解此 std::size_t pos = static_cast<size_t>(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;
}