【发布时间】:2016-10-15 19:59:50
【问题描述】:
编辑: 我更新了代码,希望现在更具体。基本上我试图使用 dlib 库来提取特征。我需要在函数 get_features(在类定义中)中使用哈希表词汇,但我想在获取函数 get_features 之前为词汇分配值,如代码中所示,这不起作用。类 feature_extractor 由 dlib 库定义。我是 c++ 和 dlib 的新手,实际上我不知道如何更好地提出我的问题。
现在我的代码结构如下:
#include <iostream>
#include <dlib/svm_threaded.h>
using namespace std;
using namespace dlib;
/*
* Read a vocabulary file and return a map of vocab
* ex. vocab["word-1"] = 0, vocab["word+0"] = 1, vocab["word+1"] = 2
*/
std::map<std::string,int> getVocab() {
std::map<std::string, int> vocab;
std::vector<string> words;
ifstream infile("filename");
string line;
while (getline(infile, line)) {
words.push_back(line);
}
int cnt = 0;
for (auto w : words) {
vocab[w] = cnt;
cnt++;
}
return vocab;
}
class feature_extractor {
public:
typedef std::vector<std::string> sequence_type;
std::map<std::string, int> vocab = getVocab(); // if put here, it does NOT work.
void get_features (
feature_setter& set_feature,
const sequence_type& sentence,
unsigned long position
) const
{
std::map<std::string, int> vocab = getVocab(); // if put here, it works.
set_feature(vocab[sentence[position]]);
}
}
int main() {
// other stuff
structural_sequence_segmentation_trainer<feature_extractor> trainer;
sequence_segmenter<feature_extractor> segmenter = trainer.train(samples, segments);
// other stuff
}
有没有一种方法可以在 get_features 函数中使用哈希表,而无需在 get_features 中调用 getVocab?也就是在函数get_features之前给变量vocab赋值,并在函数内部使用。
我尝试在 f2 之前的类定义中调用 f1 并将哈希表分配给一个变量,但它似乎不起作用。任何帮助将不胜感激。
【问题讨论】:
-
为什么会被否决?
-
@Rodger 你为什么投票?有什么好的推理吗?
-
是的,这是个好问题。我也不知道该怎么做。代码呈现出来,就会有明确的答案等等。
-
@WhozCraig 我添加了代码行,如 cmets 所示,并将尝试您的建议
-
@Hai 好的。 现在说得通了。我认为你只需要一个修改过的默认构造函数..