我应该使用什么类型的迭代器差异来消除“可能丢失数据”警告?

Ale*_*tov 5 c++ 64-bit x86 warnings visual-studio-2010

我需要 x64 模式下警告的通用规则。哪种方式更好?

考虑以下几行代码

const int N = std::max_element(cont.begin(), cont.end()) - cont.begin();
Run Code Online (Sandbox Code Playgroud)

或者

const int ARR_SIZE = 1024;
char arr[ARR_SIZE];
//...
const int N = std::max_element(arr, arr + ARR_SIZE) - arr;
Run Code Online (Sandbox Code Playgroud)

这是我常用的代码。我用 x86 没有任何问题。

但如果我在 x64 模式下运行编译器,我会收到一些警告:

conversion from 'std::_Array_iterator<_Ty,_Size>::difference_type' to 'int', possible loss of data
conversion from '__int64' to 'int', possible loss of data
Run Code Online (Sandbox Code Playgroud)

我想通过共同规则来解决这些问题。哪种方式更好?

  1. 制作static_cast

    const int N = static_cast<int>(
         std::max_element(cont.begin(), cont.end()) - cont.begin()  );
    
    Run Code Online (Sandbox Code Playgroud)

    我认为这不是通用的。而且字母太多。

  2. 将输出类型替换为ptrdiff_t

    const ptrdiff_t N = std::max_element(cont.begin(), cont.end()) - cont.begin();
    
    Run Code Online (Sandbox Code Playgroud)

    那么我应该如何处理这个未知类型 ptrdiff_t 呢?然后我会收到另外十几个警告。我想用 N 进行许多操作:保存、加法、乘法、循环等。 重要提示:但是如果std::_Array_iterator<_Ty,_Size>::difference_typeptrdiff_t是不同类型怎么办?

  3. 将输出类型替换为std::_Array_iterator<_Ty,_Size>::difference_type

    //h-file
    struct S {
        type mymember; // What is the type?
    };
    
    
    //cpp-file
    typedef std::vector<int> cont_t;
    const cont_t::difference_type N = std::max_element(cont.begin(), cont.end()) - cont.begin();
    // Save N
    S mystruct;
    mystruct.mymember = N; // What type of mystruct.mymember?
    
    Run Code Online (Sandbox Code Playgroud)

    我该如何保存N?mystruct.mymember 是什么类型?我不知道h文件中的内容。

  4. 您的解决方案。

Kir*_*sky 0

在里面visual-studio-2010你可以写:

const auto N = std::max_element( cont.begin(), cont.end() ) - cont.begin();
Run Code Online (Sandbox Code Playgroud)