如何在map容器中插入set容器的值
How to insert values of set container in a map container in C++?
我有一个如下格式的文件。
47304 - 305,463,190,444, 4, 97, 41,381,414,459,159, 75, 5,207,....
50854 - 498,214,300,274,392,390,262, 28,231,349,251, 30,254, 51,326, ..
.
.
我希望使用set作为值的map容器。
因此,我想创建一个映射容器,其中键作为"-"(即47304)之前的值,其值必须是包含"-"(即47304)之后的值的集合。305、463、444等)
同样,我想对该文件的其他行重复相同的操作。非常感谢任何帮助。由于
确实有很多很多潜在的解决方案。
通常使用带分隔符的std::getline
函数,读取到破折号或逗号。同样,regex与std::sregex_token_iterator
结合将产生非常强大的解决方案(尽管有点慢)。
但在这种情况下,我们也可以使用更简单的解决方案。
首先,我们读取一整行。这为我们提供了一点安全性,以防出现一些格式不正确的数据。这一行将被放入std::istringstream
中,这样我们就可以简单地从那里用正常的>>
操作提取数据。
为了消除破折号'-'和逗号',',',我们将使用一个虚拟的丢弃变量,并且总是读取一对字符和数字。
iss >> iss >> dummyChar >> value
将始终读取一个破折号/逗号和一个值,
这使他们的生活非常简单。
我们可以这样做,例如:
#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <set>
std::istringstream fileSimulationStream{R"(47304 - 305,463,190,444, 4, 97, 41,381,414,459,159, 75, 5,207
50854 - 498,214,300,274,392,390,262, 28,231,349,251, 30,254, 51,326)"};
int main() {
// Resulting data
std::map<int,std::set<int>> data;
// Read all lines from file
for (std::string line{}; std::getline(fileSimulationStream, line); ) {
// Put line in an istringstream for further extraction
std::istringstream iss{line};
// Get the key for the map
int key{}; iss>> key;
// Read the rest of the values in a temporary set
std::set<int> tempSet{}; char dummyChar{}; int value{};
while (iss >> dummyChar >> value) tempSet.insert(value);
// Now add everything to the map
data[key] = std::move(tempSet);
}
// Create some debug output
for (const auto&[key, set] : data) {
std::cout << key << "t--> ";
for (const int i : set) std::cout << i << ' ';
std::cout << 'n';
}
}
相关文章:
- 插入 std::set 作为 std::map 的键
- 如何将标准::矢量插入具有自定义排序功能的 std::set 中
- 如何在一对集合的向量中插入元素?vector<pair<int,set<string>>>
- 新元素将在std :: set中插入哪里
- 将排序范围插入 std::set 并带有提示
- 无法将 std::set 中的元素迭代器插入到 std::list
- 插入后使用 set::begin() 迭代器
- C++ std::map 或 std::set - 有效地插入重复项
- 排序 std::set 使用 operator() 对插入进行排序
- 在 std::set 中插入对不一致(无法识别 <pair>.second)
- 插入 Set C++ 时出错
- set<>类,当我插入类时,它不接受我的<运算符
- 拆分 std::string 并插入到 std::set 中
- 为什么编译器说我不能将项插入到 std::set 中<Item>?
- 插入适用于 set,但不适用于 unordered_set
- map/set :: 插入是否提供了正确的迭代器提示,它的复杂性是多少?
- 如何在std::set中为插入唯一元素提供比较功能
- 如何在map容器中插入set容器的值
- 为什么我的对象没有插入到std::set中
- 检测插入std::set中的坏项