繁体   English   中英

将值插入向量图<entry>

[英]insertion of values into a map of vector<entry>

我在学校为CIS算法分析课程编写程序,在如何将我从输入文件中解析的数据插入到映射(其中值是Entry类型的向量)中的过程中,我难以理解实现包含页码和范围的结构。 我已经阅读了几个小时,但似乎无法正确理解语法。

输入文件的前三行如下:

IX:{Series |(} {2} IX:{Series!geometric |(} {4} IX:{Euler's constant} {4}

基本上,我正在解析一本书的索引,当我打印地图时,它应该列出所有标题/子标题的标题和页面范围。

#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <map>

using namespace std;

#define START 0
#define END -1

struct Cmp_Insen
{
bool operator()(const string &lhs, const string &rhs) const
    {
    return stricmp(lhs.c_str(), rhs.c_str()) < 0;
    }
};

struct Entry
{
int pageNum;
int type;
};

int main( int argc, char *argv[] )
{
string inputstring, ent_nam_substring, pag_num_substring, page_number;
int ent_nam_str, ent_nam_end, pag_num_str, pag_num_end;
vector<Entry> page_range;

if( argc < 2)
    return 0;
else
{
    ifstream the_file ( argv[1] );
    if( !the_file )
        cerr<<"Could not open file!\n";
    else
    {

    map<string,vector<Entry>,Cmp_Insen> mIndex;
    //map<string,vector<Entry>,Cmp_Insen>::const_iterator iter;
    //for(iter = mIndex.begin(); iter != mIndex.end(); ++iter)


    while( !the_file.eof() )
    {
        getline( the_file, inputstring );     // Extract Entry Heading Start
        ent_nam_str = inputstring.find("{");
        ent_nam_end = inputstring.find("}");
        ent_nam_substring = inputstring.substr(ent_nam_str + 1, ent_nam_end - (ent_nam_str + 1));          // Extract Entry Heading End


        pag_num_substring = inputstring.substr(ent_nam_end + 1, inputstring.length() - ent_nam_substring.length()); // Extract Page Number Start
        pag_num_str = pag_num_substring.find("{");
        pag_num_end = pag_num_substring.find("}");
        page_number = pag_num_substring.substr(pag_num_str + 1, pag_num_end - (pag_num_str + 1));  // Extract Page Number End


    }
    }
}
return 0;

}

输入的第一行完成处理后,page_Number ='2'; 和ent_nam_substring =“系列|(”

在映射中,“系列”是该行的键,而“ |(”表示该页的页面范围的开始,该页范围从第2页开始。我需要做的是扫描输入的每一行,如果输入则插入一个键不存在,如果确实存在,则将下一个页码推到与该键关联的向量上,直到到达“ |)”为止,表示该标题的页码范围的末尾。

我的另一个相关问题是,如果我在进行不区分大小写的比较,以使地图在键上保持有序排列,我是否必须在每次或在地图声明中定义并声明比较后就显式调用比较?每当执行插入之类的操作时使用它吗?

很抱歉,我因知识不足而引起的任何困惑,由于我的两本教科书都没有为我提供所需的答案,因此非常感谢您提供任何有用的反馈。

定义比较运算符后,地图将自动自行处理其用法。 您不必调用它。

顺便说一句,stricmp不可移植。 在Unux上,您可能需要strcasecmp。 这应该可以解决问题:

#ifndef WIN32 
  #define stricmp strcasecmp 
#endif

关于其余的问题,您解释了代码应执行的操作,但是您忘了提及它实际上在做什么……

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM