这是我的代码:
#include <iostream>
#include <vector>
void cumulative_sum_with_decay(std::vector<double>& v)
{
for (auto i = 2; i < v.size(); i++) {
v[i] = 0.167 * v[i - 2] + 0.333 * v[i - 1] + 0.5 * v[i];
}
}
void printv(std::vector<double>& v)
{
std::cout << "{";
for (auto i = 0; i < v.size() - 1; i++) {
std::cout << i << ", ";
}
std::cout << v[v.size() - 1] << "}\n";
}
int main()
{
auto v = std::vector<double>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cumulative_sum_with_decay(v);
printv(v);
}
当我尝试编译并运行该程序时,收到以下警告:
$ clang++ -std=c++11 -Wextra foo.cpp && ./a.out
foo.cpp:6:24: warning: comparison of integers of different signs: 'int' and 'std::__1::vector<double,
std::__1::allocator<double> >::size_type' (aka 'unsigned long') [-Wsign-compare]
for (auto i = 2; i < v.size(); i++) {
~ ^ ~~~~~~~~
foo.cpp:14:24: warning: comparison of integers of different signs: 'int' and 'unsigned long'
[-Wsign-compare]
for (auto i = 0; i < v.size() - 1; i++) {
~ ^ ~~~~~~~~~~~~
2 warnings generated.
{0, 1, 2, 3, 4, 5, 6, 7, 8, 8.68781}
如何初始化用
auto
声明的这些循环计数器,以使代码安全并且没有警告?请注意,尽管这里的 vector 很小,但是即使 vector 很大,
auto
中的值可能会超出整数范围,我仍在尝试学习如何用i
编写安全代码。 最佳答案
从初始化程序推导auto
声明的变量的类型。给定2
或0
,它将为int
。
您可以使用显式键入的初始值设定项指定类型。例如
for (auto i = static_cast<decltype(v.size())>(2); i < v.size(); i++) {
关于c++ - 如何初始化用auto关键字声明的循环计数器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50502632/