首页 > 解决方案 > 混淆有符号和无符号整数

问题描述

我正在尝试使用Fenwick tree从这里解决这个问题。我的代码如下:

class BIT {
public:
    BIT(std::vector<int> list) {
        m_array = std::vector<int>(list.size() + 1, 0);
        for (int idx = 0; idx < list.size(); idx++) {
            update(idx, list[idx]);
        }
    }


    int prefix_query(int idx) const {
        int result = 0;
        for (++idx; idx > 0; idx -= idx & -idx) {
            result += m_array[idx];
        }
        return result;
    }

    int range_query(int from_idx, int to_idx) const {
        // Computes the range sum between two indices (both inclusive)
        if (from_idx == 0)
            return prefix_query(to_idx);
        else
            return prefix_query(to_idx) - prefix_query(from_idx - 1);
    }

    void update(int idx, int add) {
        // Add a value to the element at index idx
        for (++idx; idx < m_array.size(); idx += idx & -idx) {
            m_array[idx] += add;
        }
    }

private:
    std::vector<int> m_array;
};

int main () {
    int n, q, a, b, c;
    std::cin >> n >> q;
    std::vector<int> vec(n+1);
    for(int i = 1; i < n + 1; i++){
        std::cin >> a;
        vec.push_back(a);
    }
    BIT bit(vec);
    for(int i = 0; i < q; i++){
        std::cin >> b >> c;
        std::cout << bit.range_query(b, c) << std::endl;
    }
}

我从在线法官那里得到了这些编译器警告 在此处输入图像描述

我尝试将 idx 转换为有符号的数字,(signed) idx但是当我这样做时,代码会为我输入的任何值返回 0。我不明白出了什么问题,因为它在我的机器上运行良好,但在线法官中的 C++ 编译器对于建议任何有用的东西并不是很有帮助。

标签: c++algorithm

解决方案


std::vector::size通常是类型size_t,它是无符号的。因此,将 idx 强制转换或声明为无符号类型应该可以修复编译器警告。


推荐阅读