无法成功生成文件和控制台的std::set输出
Can not successfully generate the std::set output to the file and console
我正在尝试从文件中读取一个整数列表,并将它们存储到std::set
容器中,然后将整数输出到控制台,然后生成输出文件。我试过做那件事,但没能成功。如果我在程序中使用.erase()
,那么我可以在控制台上看到输出和一个没有文本的空文件。如果我不使用.erase()
,那么我有无限循环的运行时错误
#include <iostream>
#include <set>
#include <fstream>
#include <iterator>
using namespace std;
int main()
{
set<int> myset;
fstream textfile;
textfile.open("input.txt"); // opening the file
// reading input from file
while (!textfile.eof())
{
int iTmp = 0;
textfile >> iTmp;
myset.insert(iTmp);
}
// output to the console
set<int>::iterator iter = myset.begin();
while (!myset.empty())
{
cout << *myset.begin() << " ";
myset.erase(myset.begin());
}
// writting output to the file
ofstream out_data("Ahmad.txt");
while (!myset.empty())
{
out_data << *myset.begin() << " ";
}
system("pause");
}`
#include <iostream>
#include <iterator>
#include <set>
using namespace std;
int main() {
using data_type = int;
set<data_type> data_set;
//change cin to your ifstream
copy(istream_iterator<data_type>(cin),
istream_iterator<data_type>(),
inserter(data_set, end(data_set)));
//change cout to your ofstream
copy(begin(data_set), end(data_set), ostream_iterator<data_type>(cout, " "));
return 0;
}
示例:http://ideone.com/1Cil1C
您没有正确使用iterator
。
set<int>::iterator iter = myset.begin();
ofstream out_data("Ahmad.txt");
for(; iter != myset.end(); iter++)
{
cout << *iter << " ";
out_data << *iter << " ";
}
在显示的循环中擦除它们
// output to the console
for (auto& x : myset)
cout << x << " ";
// writting output to the file
ofstream out_data("Ahmad.txt");
for (auto& x : myset)
out_data << x << " ";
相关文章:
- 在声明中合并两个常量"std::set"(不是在运行时)
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将 std::set 与基于键的比较器一起使用
- 修改"std::set"中用户定义类型的值
- 如何在构造函数参数中初始化"std::set"?
- 如何使用 lower_bound/upper_bound 从 std::set 获取索引号?
- 如何在 C++ 中转发声明 std::set?
- 重构使用动态强制转换的 std::set 的比较运算符
- 为什么 std::set.erase(first, last) 会影响从中获取 (first, last) 的容器?
- std::set 是否将对象连续存储在内存中?
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- 有什么理由不扩展 std::set 以添加下标运算符吗?
- 我从 std::set 得到const_iterator而不是迭代器
- 为什么 std:set(带有单个冒号)可以编译?
- 遍历 std::set 中包含的所有三重不同值?
- 插入 std::set 作为 std::map 的键
- 如何在 c++ 中使用默认值将 std::set 转换为 std::map
- 错误:'class std::unique_ptr<std::set<long unsigned int> >'没有名为 'size' 的成员
- 如何从 std::set 绘制 n 个元素的样本
- 为什么 std::set 容器使用的内存比其数据大小多得多?