MRE(因为许可证问题):
std::set<std::string> pool;
// values: 10 10 1 3 4 3 3 2 5 7 5 4 3 9 8 8 7
// (values is an iterable collection)
for (const auto& value : values) {
pool.insert(value);
}
// expected read: 10 1 3 4 2 5 7 9 8
// actual read: 1 10 2 3 4 5 7 8 9 (10 after 1 because std::string)
Run Code Online (Sandbox Code Playgroud)
我应该使用什么集合来实现这一目标?
使用 2 个容器。读入集合,使用 insert 的返回值来确定该项目是否是新的。然后仅将新项目添加到向量中。该向量将是插入顺序中的唯一项。
#include <vector>
#include <set>
#include <string>
#include <iostream>
int main()
{
std::vector<std::set<std::string>::iterator> itemsInOrder;
std::set<std::string> pool;
std::vector<std::string> values = {"10", "10", "1", "3"};
for (const auto& value : values)
{
auto ret = pool.insert(value);
if (ret.second)
{
itemsInOrder.push_back(ret.first);
}
}
for (auto item : itemsInOrder)
{
std::cout << *item << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
99 次 |
| 最近记录: |