我是一个非常糟糕的 C++ 程序员,但为了工作,我必须将数字库从 Python 重写为 C++。
因为我有很多常量,所以我决定将它们存储在 std::map
中。
所以我有一个 vector_dict.h
文件,其中包含以下 typedef
(我正在使用 armadillo 库进行与 vector 相关的计算):
namespace klib {
typedef std::map<std::string, arma::vec> vector_dict; // a map of strings to vectors, used to store particle and interaction data
}
然后我有一个particledata.h
文件,其中包含
#include "vector_dict.h"
namespace klib {
extern klib::vector_dict atom_data;
extern klib::vector_dict molecule_data;
}
particledata.cpp
中的实现如下所示:
#include "particledata.h"
arma::vec klib::atom_data["N"] = arma::vec::fixed<4>();
double klib::atom_data["N"][0] = 14.0067; // nitrogen atom mass, atomic mass units
我正在使用 XCode(Apple LLVM 版本 5.1 (clang-503.0.40)(基于 LLVM 3.4)),它显示两行中都有一个错误:具体来说,它说“数组大小有非-整数类型 'const char[2]'。
为了测试发生了什么,我创建了一个单独的项目,其中所有内容都在一个文件中,下面的代码编译得很好:
#include <iostream>
#include <armadillo>
#include <string>
#include <map>
int main(int argc, const char * argv[])
{
typedef std::map<std::string, arma::vec> vector_dict;
vector_dict vv;
vv["N"] = arma::vec::fixed<4>();
vv["N"][0] = 34.5;
vv["N"][1] = 44.5;
vv["N"][2] = 54.5;
vv["N"][3] = 64.5;
return 0;
}
那么我哪里搞砸了?
最佳答案
从您的代码片段中看不太清楚,但看起来您可能将该代码放在 particledata.cpp 的中间位置而不是函数中。试试这个。
头文件:
namespace klib
{
extern const klib::vector_dict atom_data;
}
源文件:
namespace
{
klib::vector_dict create_atom_data()
{
klib::vector_dict atom_data;
atom_data["N"] = arma::vec::fixed<4>();
atom_data["N"][0] = 14.0067;
return atom_data;
}
}
extern const klib::vector_dict klib::atom_data = create_atom_data();
我把 map 设为const,防止创建后被修改,这样可以防止意外。如果您确实想在创建 map 后对其进行修改,只需从上面的代码中删除常量即可。
关于c++ - 无法设置 std::map 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25187276/