在c++中将令牌加载到映射容器中

Loading tokens into map container in C++

本文关键字:映射 令牌 c++ 加载      更新时间:2023-10-16

我需要在容器中加载每个子字符串/令牌的帮助。在我的代码中,我将每个单独的行从文件中分离出来,并将其置于这种格式中。

Element1 Key1 Key2 Key3(以此类推)

之后,我将每个单独的子字符串分开。问题是,我不知道如何把它放到map <字符串,set>> subjects;容器。下面是我现在的代码:

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
using namespace std; 
bool transform  ( const char * inFile,
              const char * outFile )
{
  map<string, set<string> > subjects;
  ifstream inf(inFile);
  ofstream outf(outFile);
  string line;
  while(getline(inf, line))
   {
      if(line[0]=='#') continue; // skipping of the commented lines
      int len;
      len=line.length();
      for(int i=0; i<(len-1);i++) // putting space on the place of ':' and ','
       {
           if(line[i]==':' || line[i]==',') {line[i]=' ';}
       }
      for(int i=0; i<(len-1);i++) //merging of the duplicated white spaces
       {
           if(line[i]==' ' && line[i+1]==' ') {line[i]=0;}
       }
      string s;
      istringstream f(line);
      while (std::getline(f, s, ' ')) //tokenization
       {
           //here i need to load each sub-string in the container, the first is element and after that comes the keys.
       }
   }
  return 0;
}

我是c++的新手,所以我甚至不确定如何使用容器。我有一行,第一个地方是元素,然后是元素连接的键。最后,我需要在每行上打印一个键和与此键连接的所有元素。我将非常感谢任何帮助。

通常用于抽取映射的代码<字符串,set><字符串>>看起来像这样…

这段代码假设所有奇怪的标记等都封装在这里没有定义的FileReader类中。

std::map <string, std::set<string> > FileToStringMap (std::string filename)
{
  FileReader my_reader (filename);
  std::map <string, std::set<string> > my_map;
  std::string curr_key;
  while (my_reader.getKey(curr_key))
  {
    std::set<string> value_set;
    std::string curr_value_elem;
    while (my_reader.getValue(curr_value_elem))
    {
      value_set.insert(curr_value_elem);
    }
    my_map.insert (std::make_pair(curr_key, value_set));
  }
  return my_map;
}

关于表示法的说明:通常,map的第一个元素类型称为,其他数据称为。我在我的代码中使用这种做法,即使在您的问题中,术语的使用方式不同。

您不需要替换分隔符; , <space>,只需使用它们。这是一个示例代码,它返回字符串向量(在您的情况下)

std::vector keys;
std::string element1;
size_t last_cur_pos = 0;
for(std::size_t i = 0; i < line.length(); i++)
{
    if( line[i]==':' || line[i]==',' || line[i] == ' ' || i == (line.length()-1))
    {
        std::string temp = line.substr(last_cur_pos, (i-last_cur_pos));
        if(last_cur_pos == 0)
           element1 = temp;
        else
           keys.push_back(temp);
        last_cur_pos = i + 1;
    }
}
// Considering your map is subjects<string, vector<string>> then;
subjects[element1] = keys;