引言:
int mAIn()
{
std::vector<uint32_t> vec;
// 填充向量
for(int i=0; i<10000000; i++)
{
vec.push_back(i);
}
// 对向量的值进行1000次求和
for (int i = 0; i < 1000; i++)
{
uint64_t sum = 0;
for (std::vector<uint32_t>::const_iterator itr = vec.begin();
itr != vec.end();
itr++)
{
sum += *itr;
}
std::cout << sum << std::endl;
}
}
int main()
{
std::vector<uint32_t> vec;
for(int i=0; i<10000000; i++)
{
vec.push_back(i);
}
for (int i=0; i<1000; i++)
{
uint64_t sum = 0;
// 缓存vec.end()以避免重复查找
std::vector<uint32_t>::const_iterator itr, end(vec.end());
for (itr = vec.begin();
itr != end;
itr++)
{
sum += *itr;
}
std::cout << sum << std::endl;
}
}
int main()
{
std::vector<uint32_t> vec;
// 使用前置递增代替后置递增
for(int i=0; i<10000000; ++i)
{
vec.push_back(i);
}
for (int i=0; i<1000; ++i)
{
uint64_t sum = 0;
std::vector<uint32_t>::const_iterator itr, end(vec.end());
// 使用前置递增代替后置递增
for (itr = vec.begin();
itr != end;
++itr)
{
sum += *itr;
}
std::cout << sum << std::endl;
}
}
struct Sum
{
uint64_t m_sum;
Sum()
: m_sum(0)
{
}
void operator()(uint32_t i)
{
m_sum += i;
}
};
struct Increment
{
int m_value;
Increment(int i)
: m_value(i)
{
}
int operator()()
{
return m_value++;
}
};
int main()
{
std::vector<uint32_t> vec;
// 使用Increment生成器生成10000000个值
std::generate_n(back_inserter(vec), 10000000, Increment(0));
for (int i = 0; i < 1000; ++i)
{
uint64_t sum = 0;
// 使用std::for_each进行循环求和
std::for_each(vec.begin(), vec.end(), Sum(sum));
std::cout << sum << std::endl;
}
}