gpt4 book ai didi

c++ - 在类类型 vector 中引用对象的成员

转载 作者:搜寻专家 更新时间:2023-10-31 00:42:20 25 4
gpt4 key购买 nike

好吧,这个问题困扰了我一整天,我似乎找不到解决方案。我知道这是一篇很长的文章,但如果您能提供任何帮助,我将不胜感激。我正在开发一个聊天机器人程序,该程序从 .dat 文件中读入以填充关键字库。采用面向对象的方法,我定义了一个名为“Keyword”的类,类定义如下所示:

class Keyword
{
public:
//_Word holds keyword
vector<string> _Word;
//_Resp holds strings of responses
vector<string> _Resp;
//_Antymn holds words that are the opposite to keyword
vector<string> _Antymn;

// Constructor
Keyword()
{
// Clears members when new instance created
_Word.clear();
_Resp.clear();
_Antymn.clear();
}
};

因此,每次在 .dat 文件中发现新关键字时,都必须创建该类关键字的新实例。为了存储关键字的所有这些实例,我创建了另一个 vector ,但这次是关键字类型并将其称为库:

typedef vector<Keyword> Lib;
Lib library;// this is the same as saying vector<Keyword> library

现在这是我遇到的问题:在用户输入字符串后,我需要检查该字符串是否包含库中的关键字,即我需要查看 _Word 中的字符串是否出现在用户输入中。从你拥有的 vector 层次结构来看:

The top level --> libary //*starting point
--> Keyword
--> _Word
-->"A single string" <-- I want to reference this one
--> _Resp
-->"Many strings"
--> _Antymn
-->"Many strings"

呸!我希望这是有道理的。这是我开始写的代码:

size_t User::findKeyword(Lib *Library)
{
size_t found;
int count = 0;

for(count = 0; count<Library->size(); count++)
{
found = _Input.find(Library->at(count)); // this line needs to reference _Word from each keyword instance within library
if(found!= string.npos)
return found;
}

return 0;
}

我也曾尝试使用“operator[]”方法,但它似乎也无法满足我的要求。有人有什么主意吗 ?如果无法完成,我会感到非常惊讶。提前谢谢你。

最佳答案

首先是一堆问题:

  • 以下划线开头,后跟大写字母的标识符字母在任何命名空间中都保留
  • Keyword 构造函数中的 clear() 调用毫无意义,而且可能不利于优化

为什么 word_ 是一个vector?我虽然是一个关键字。

struct Keyword
{
// real words as identifiers, no underscores
//anywhere if they are public
std::string word;
std::vector<std::string> respones;
std::vector<std::string> antonym;
};


typedef std::vector<Keyword> Lib;



/// finding a keyword
#include <algorithm>

Lib::iterator findKeyword(const Lib& l, const std::string& x) {
return std::find_if(begin(l), end(l),
[](const Keyword& kw) { return kw.word == x; })
// if stuck on non C++11 compiler use a Functor
}

关于c++ - 在类类型 vector 中引用对象的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12113644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com