例子1:使用输入迭代器读取文件中的数据
例子2:使用输出迭代器将数据写入文件
例子3:使用双向迭代器反转容器中的元素
例子4:使用随机访问迭代器进行二分查找
下面的代码演示了如何使用输入迭代器从文件中读取数据,并计算其平均值。
#include
#include
#include
#include
int main()
{
std::ifstream file("data.txt");
std::istream_iterator begin(file), end;
int sum = std::accumulate(begin, end, 0);
int count = std::distance(begin, end);
double avg = static_cast(sum) / count;
std::cout << "Average: " << avg << std::endl;
return 0;
}
在上面的代码中,我们使用了std::ifstream
来打开文件,然后将其传递给std::istream_iterator
。接下来,我们使用std::accumulate
和std::distance
算法来分别计算文件中所有整数的总和和个数,最后计算平均值并输出结果。
课程概述(课程共7300字,8个代码举例)
2.1 输入迭代器
2.2 输出迭代器
2.3 前向迭代器
2.4 双向迭代器
代码例子说明
例子1:使用输入迭代器读取文件中的数据
例子2:使用输出迭代器将数据写入文件
例子3:使用双向迭代器反转容器中的元素
例子4:使用随机访问迭代器进行二分查找