如果在vscode能运行,就是C++版本的问题,VS2010仅支持部分C++11及以上的功能,仍然有一小部分不支持,但是他的警告信息和错误信息又很不明显,所以花了很多时间纠错。
总结:
看这三种for循环
for (const Product& product : products) {
if (product.type == TYPE_A) {
sumA += product.price;
countA += 1.0;
} else if (product.type == TYPE_B) {
sumB += product.price;
countB += 1.0;
}
}
这段代码使用了 C++11 引入的范围-based for 循环,也称为 foreach 循环。在这个循环中,我们不需要通过迭代器或者索引来遍历容器,而是直接使用类似于数组的方式来遍历容器中的元素。这种语法使得代码更加简洁易读。在vs2010中会报错。
for (vector<Product>::const_iterator it = products.begin(); it != products.end(); ++it) {
const Product& product = *it;
if (product.type == TYPE_A) {
sumA += product.price;
countA += 1.0;
} else if (product.type == TYPE_B) {
sumB += product.price;
countB += 1.0;
}
}
这段代码使用了一个 vector<Product>::const_iterator 类型的迭代器 it 来遍历 products 容器。通过 it-> 访问迭代器指向的对象 ,在vs2010也会报错。
for (int i = 0; i < products.size(); ++i) {
const Product& product = products[i];
if (product.type == TYPE_A) {
sumA += product.price;
countA += 1.0;
} else if (product.type == TYPE_B) {
sumB += product.price;
countB += 1.0;
}
}
这种是最普通的 for 循环和索引 i 来遍历 products 容器。在循环体内,我们通过索引 i 访问容器中的元素,所以在vs2010适用。