在c++中将令牌加载到映射容器中
Loading tokens into map container in C++
我需要在容器中加载每个子字符串/令牌的帮助。在我的代码中,我将每个单独的行从文件中分离出来,并将其置于这种格式中。
Element1 Key1 Key2 Key3(以此类推)
之后,我将每个单独的子字符串分开。问题是,我不知道如何把它放到map <字符串,set>
#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;
相关文章:
- 如何在C++中使用X509证书模在令牌中查找私钥
- holeMenuProgram.cpp:38:1 错误:'}'令牌之前的预期主表达式
- C++:"("令牌"之前有预期的非限定 id 指向类中成员函数的指针
- Arduino 用于语句错误。令牌之前的预期')' ';'。如何解决这个问题?
- 错误:令牌 { '{' 之前应存在非限定 ID
- 允许哪些令牌作为 #include 的参数?
- "错误 C0000:语法错误,令牌"<EOF>"处出现意外$end,并且不确定
- 它在 { 令牌之前给了我预期的标识符
- (错误:令牌之前'<<'预期的主表达式)
- 为什么 ## aka 令牌粘贴运算符不适用于 C 和 C++ 中的注释?
- 错误:"->"令牌之前的预期初始值设定项
- LINUX 操作系统上的错误:令牌之前预期的构造函数、析构函数或类型转换'('?
- 丢失读入的每一行输入中的最后一个令牌
- 如何使用 libCurl 将访问令牌发送到服务器 API
- C++令牌定义成员
- 宏定义中的预处理器令牌两边有两个双引号
- 错误:C++中']'令牌之前的预期主表达式
- 错误:令牌之前的预期主表达式'&&'
- 令牌之前']'预期的主表达式?
- 用于将整数映射到令牌的字符串的宏