c++ - 混淆有符号和无符号整数
问题描述
我正在尝试使用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++ 编译器对于建议任何有用的东西并不是很有帮助。
解决方案
std::vector::size
通常是类型size_t
,它是无符号的。因此,将 idx 强制转换或声明为无符号类型应该可以修复编译器警告。
推荐阅读
- python - QTableView HorizontalHeader 让它非常滞后?
- uwp - 是否需要 Windows 应用程序认证套件流程?
- typescript - 如何获取类中静态方法的名称?
- c# - 错误 MySql 您的 SQL 语法有错误。添加带有变量的参数时
- flutter - 来自时间选择器的 Flutter Format Time of Day
- spring-boot - SpringBoot 应用程序无法解析 thymeleaf 视图
- asp.net-core - 我想在详细信息页面中而不是在 AspNetCore Web 应用程序的索引页面中构建列
- javascript - 如何包含第三方 javascript
- sql-server - xp_dirtree 从一张表的一个文件夹中加载所有 csv 文件
- html - 如果 Delphi 不能提供汇编,如何为 Delphi 构建 Sandcastle Microsoft Help 2.0 文档?