3 回答

TA貢獻1862條經驗 獲得超6個贊
向后迭代
看到這個答案。
迭代轉發
這幾乎是相同的。只需按增量更改迭代器/交換遞減量即可。您應該更喜歡迭代器。有人告訴您將其std::size_t用作索引變量類型。但是,這不是便攜式的。始終使用size_type容器的typedef(雖然在向前迭代的情況下只能進行一次轉換,但是在使用時std::size_t,如果向后迭代的情況下它可能會出錯,以防萬一std::size_t大于typedef的情況size_type) :
使用std :: vector
使用迭代器
for(std::vector<T>::iterator it = v.begin(); it != v.end(); ++it) {
/* std::cout << *it; ... */
}
重要的是,對于您不知道其定義的迭代器,請始終使用前綴增量形式。這將確保您的代碼盡可能地通用。
使用范圍C ++ 11
for(auto const& value: a) {
/* std::cout << value; ... */
使用索引
for(std::vector<int>::size_type i = 0; i != v.size(); i++) {
/* std::cout << v[i]; ... */
}
使用數組
使用迭代器
for(element_type* it = a; it != (a + (sizeof a / sizeof *a)); it++) {
/* std::cout << *it; ... */
}
使用范圍C ++ 11
for(auto const& value: a) {
/* std::cout << value; ... */
使用索引
for(std::size_t i = 0; i != (sizeof a / sizeof *a); i++) {
/* std::cout << a[i]; ... */
}
但是,請閱讀向后迭代的答案,該sizeof方法可以解決什么問題。

TA貢獻2039條經驗 獲得超8個贊
在您的示例的特定情況下,我將使用STL算法來完成此操作。
#include <numeric>
sum = std::accumulate( polygon.begin(), polygon.end(), 0 );
對于更一般但仍然非常簡單的情況,我將使用:
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
using namespace boost::lambda;
std::for_each( polygon.begin(), polygon.end(), sum += _1 );
- 3 回答
- 0 關注
- 795 瀏覽
添加回答
舉報