如何在map容器中插入set容器的值

How to insert values of set container in a map container in C++?

本文关键字:set 插入 map      更新时间:2023-10-16

我有一个如下格式的文件。

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';
    }
}