c++ - 拆分 std::string 并插入 std::set

标签 c++

根据 C++ 聊天室的奇人的要求,分解文件(在我的例子中包含一个大约 100 行的字符串,每行大约 10 个单词)并插入的好方法是什么所有这些词都变成一个 std::set?

最佳答案

从包含一系列该元素的源构造任何容器的最简单方法是使用采用一对迭代器的构造函数。使用 istream_iterator 迭代流。

#include <set>
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>

using namespace std;

int main()
{
  //I create an iterator that retrieves `string` objects from `cin`
  auto begin = istream_iterator<string>(cin);
  //I create an iterator that represents the end of a stream
  auto end = istream_iterator<string>();
  //and iterate over the file, and copy those elements into my `set`
  set<string> myset(begin, end);

  //this line copies the elements in the set to `cout`
  //I have this to verify that I did it all right
  copy(myset.begin(), myset.end(), ostream_iterator<string>(cout, "\n"));
  return 0;
}

http://ideone.com/iz1q0

关于c++ - 拆分 std::string 并插入 std::set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11146379/

相关文章:

c++ - 如何使用 Beast C++ 库从 HTTP 重定向到 HTTPS?

C++ 链表和节点模板链接错误

c++ - Bithacking 比较(较少)运算符

c++ - 格罗马克 : Illegal instruction (core dumped)

python - 如何在 CuPy 中分配倾斜的 2D 内存?

javascript - Node.js 错误 "terminate called after throwing an instance of ' std::bad_alloc' what(): std::bad_alloc"

java - 实现 LRU 缓存的最佳方法

c++ - Windows Server 2012 中 DLL 无法加载

c++ - 比较列表并给出列表 b 中不在列表 a 中的内容

Java 泛型和 C++ 模板