[英]Referencing members of an object within a class type vector
好的,這個問題整天困擾着我,我似乎找不到解決方法。 我知道這是一篇很長的文章,但是如果您能提供任何幫助,我將不勝感激。 我正在研究一個聊天機器人程序,該程序從.dat文件讀取以填充關鍵字庫。 使用面向對象的方法,我定義了一個名為“關鍵字”的類,該類的定義如下所示:
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文件中找到新的關鍵字時,都必須創建class關鍵字的新實例。 為了存儲關鍵字的所有這些實例,我創建了另一個向量,但是這次是關鍵字類型,並將其稱為庫:
typedef vector<Keyword> Lib;
Lib library;// this is the same as saying vector<Keyword> library
現在這是我遇到的問題:用戶輸入一個字符串后,我需要檢查該字符串是否包含來自庫的關鍵字,即,我需要查看_Word中的字符串是否出現在用戶輸入中。 從向量的層次結構來看它:
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
}
您必須將代碼更改為此:
for(count = 0; count<Library->size(); count++)
{
for(int j = 0; j < Library->at(count)._Word.size(); ++j){
found = _Input.find(Library->at(count)._Word[j]);
^^^^^^^^^
if(found!= string.npos)
return found;
}
}
為了訪問成員變量並遍歷字符串向量。 Library->at(count)
是Keyword
類的對象。 我假設_Input.find()
將字符串作為參數。
如果您的Keyword
實例僅存儲一個關鍵字,則最好將其更改為string _Word
,這樣您就不需要第二個循環。
for(count = 0; count<Library->size(); count++)
{
found = _Input.find(Library->at(count)._Word);
if(found!= string.npos)
return found;
}
而且還可以執行其他意見:你不應該使用的初步_
-underscore在變量名,因為它們是由執行保留。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.