c ++优先顺序 - 在乘法之前进行铸造

c++ order of precedence - casting before multiplying

在下面的 C++ 函数中,为什么 numbers[max_index1] 转换为 long long 然后乘以 numbers[max_index2]?我会认为你会乘以数字然后投射?

此外,将矢量数字类型设为 long long 而不是 int 是否更有意义,因此不需要强制转换?

long long MaxPairwiseProductFast(const vector<int>& numbers) {

    int n = numbers.size();

    int max_index1 = -1;
    cout << "value at max_index1 is " << numbers[max_index1] << std::endl;
    for(int i = 0; i < n; i++)
        if((max_index1 == -1) || (numbers[i] > numbers[max_index1]))
            max_index1 = i;


    int max_index2 = -1;
    for(int j = 0; j < n; j++)
        if((numbers[j] != numbers[max_index1]) && ((max_index2 == -1) || (numbers[j] > numbers[max_index2])))
            max_index2 = j;

    return ((long long)(numbers[max_index1])) * numbers[max_index2];
}

int main() {
    int n;
    cin >> n;
    vector<int> numbers(n);
    for (int i = 0; i < n; ++i) {
        cin >> numbers[i];
    }

    long long result = MaxPairwiseProductFast(numbers);
    cout << result << "\n";
    return 0;
}
((long long)(numbers[max_index1])) * numbers[max_index2];

numbers[max_index2] 将在执行乘法之前提升为 long long。 如果将两个 int's 相乘并且结果溢出,则将该结果转换为 long long 无法实现任何结果,因此您先 cast,然后再相乘。

Also would be not make more sense to make the vector numbers type long long instead of int therefore the casting wouldn't be necessary?

如果您知道单个数字适合 int,但两个 int's 相乘的结果可能会溢出,这将有助于节省 space。

I woudld of thought that you'd multiply the numbers and then cast?

假设您的两个操作数的值为 std::numeric_limits<int>::max()。这是一个 int 可以表示的最大值,并且(因为它是一个正整数)这个数字的平方结果是 甚至更大 .

当您将两个 int 值相乘时,结果也是 int。请参阅 here(特别是 有符号 类型的转换、整数提升和溢出)。

由于结果根据定义大于您可以存储在 int 中的最大值,因此与 ints 进行此乘法运算会得到未定义的结果。您需要使用足够大的类型来执行乘法以存储结果。