这是我的代码:
#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
声明的这些循环计数器,以便代码安全且没有警告?
请注意,虽然我在这里有一个小向量,但我正在尝试学习如何使用auto
编写安全代码,即使向量太大以至于i
中的值可能超出范围整数。
答案 0 :(得分:8)
您可以使用&#39; decltype(v.size())&#39;得到正确的类型。
for (decltype(v.size()) i = 2; i < v.size(); i++)
答案 1 :(得分:5)
auto
- 声明变量的类型是从初始化程序中推导出来的。给定2
或0
,它将int
。
您可以使用显式类型化的初始值设定项指定类型。 e.g。
for (auto i = static_cast<decltype(v.size())>(2); i < v.size(); i++) {
答案 2 :(得分:0)
这不是你的问题的答案,但它解决了使用迭代器的问题。
void cumulative_sum_with_decay(std::vector<double>& v)
{
assert(v.size()>2);
for (auto it = v.begin()+2; it!=v.end(); it++) {
*it = 0.167 * *(it-2) + 0.333 * *(it-1) + 0.5 * *it;
}
}
void printv(std::vector<double>& v)
{
assert(v.size()>0);
std::cout << "{";
for (auto it = v.begin(); it != v.end() - 1; it++) {
std::cout << *it << ", ";
}
std::cout << v.back() << "}\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);
}
答案 3 :(得分:-3)
auto i=2
表示a是int
类型&amp; vector.size()
是size_t,这就是为什么-Wsign-compare来了。你可以用
for (std::size_t i = 0, max = vec.size(); i != max; ++i)
或
for (auto it = vec.begin(), end = vec.end(); it != end; ++it)