无法将元素添加到 STL 地图

Not able to add elements to STL map

我正在用 C++ 编写一个文本文件解析器。为此,我必须在地图中存储 "valueToParse"(字符串类型)及其对应的正则表达式(字符串类型)。我在 .h 文件中定义了地图并将其包含在 main 中。在构建解决方案时,我观察到如下错误:

error C2057: expected constant expression c:\mypractice\hobbyprojects\MyParser\logparser.h

error C2466: cannot allocate an array of constant size 0 c:\mypractice\hobbyprojects\MyParser\logparser.h

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\mypractice\hobbyprojects\MyParser\logparser.h

error C2040: 'ValuesToParse' : 'int []' differs in levels of indirection from 'std::map<_Kty,_Ty>' c:\mypractice\hobbyprojects\MyParser\logparser.h

error C2440: 'initializing' : cannot convert from 'const char [4]' to 'int []' c:\mypractice\hobbyprojects\MyParser\logparser.h

我的 C++ 代码如下:

main.cpp

#include <iostream>
#include <regex>
#include "logParser.h"
int main()
{
    return 0;
}

logParser.h:

#pragma once
#include <string>
#include <map>

std::map<std::string, std::string> ValuesToParse;
ValuesToParse["FileName"] = "xyz";  
ValuesToParse["Author"] = "abc";

logParser.cpp

#include "logParser.h"

我用谷歌搜索了错误,但没有成功。请不要介意我是 C++ 的新手。谁能帮我理解这个?

您有两个个问题:

首先是您在头文件中定义一个变量。这意味着它将在包含头文件的每个 translation unit 中定义。不过,那不是您 当前 问题的根源。

第二个问题,也是导致错误的原因,是您在函数之外有通用语句。在函数之外你只能有 declarationsdefinitions.

这两个问题的答案都在您的课本中。

您有全局范围内的代码,需要将其放入函数中(logparser.cpp),例如:

void initialize()
{
  ValuesToParse["FileName"] = "xyz";  
  ValuesToParse["Author"] = "abc";
}

然后将声明插入头文件

void initialize();

并在 main() 函数中调用它