gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:53:29 25 4
gpt4 key购买 nike

根据 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com