C++词表;在矢量/地图中找到完整的描述

C++ Wordlist; find a whole describtion in vector/map

本文关键字:描述 地图 词表 C++      更新时间:2023-10-16

如果你创建一个单词列表,我正在制作一个代码。它包含一个"单词"和一个"描述"。单词和描述有自己的向量。我也在使用地图来尝试同样的方法。

该程序进展顺利,直到我尝试查找单词为止。该程序只会从描述中获取最后一个词。有没有办法将整个句子变成一个向量?

这是我如何写下描述的代码。整个程序代码真的很长,所以我只提到重要的东西:

cout<< "Describe your word:"; //Describtion by using vectors
cin>> desc;         //Here you enter the decribtion
getline(cin, desc); //So you can have "space" and write a whole sentence.
d.push_back(desc);  //Place the describe at the back of the list so it is at the same index as the matching word

这是应该显示单词和描述的代码:

cout<< "Enter a word to lookup:";
cin>> word;
if (find(o.begin(), o.end(), word) !=o.end())   //Lookup if word excist in vector
{
    int pos = find(o.begin(), o.end(), word) - o.begin();   //Searches which index the word is in the vector
    cout<< "Describtion for " << word << " is " << d[pos] << endl;  //d[pos] takes the description vector that is in the same index as the word vector
}
else
    cout<< "Word not found! Try something else." << endl;   //If word not found

它只会从描述中取出最后一个词。我通过使用地图遇到了同样的问题:

cout<< "Enter a word to lookup:"; 
cin>> word;
if (L.find(word) != L.end())    //Lookup if the key excist
{
    cout<< "Describtion for " << word << " is " << L[word] << endl; //Tells what the description is for the word if it excist
}
else
    cout<< "Word not found! Try something else." << endl;   //Tells you this if key is not found

那么,我怎样才能打印出特定单词的整个描述呢?

编辑:我注意到它只是描述中缺少的第一个单词(我很愚蠢,不会尝试使用超过 2 个单词(

那么,出了什么问题呢?如何在输出的描述中获取描述中的第一个单词?

如果你从std::cin中提取一个std::string,它只会得到一个单词。首先,您获得描述的第一个单词并将其放入desc

cin >> desc;         // Here you enter the decribtion

然后,您将获得描述中剩余的单词并将它们放在desc中。覆盖desc的先前内容(第一个单词(:

getline(cin, desc); // So you can have "space" and write a whole sentence.

因此,现在desc包含描述中除第一个单词之外的所有内容。请考虑使用调试器来查找此类内容。

其他一些建议:避免搜索两次vector。将find的结果存储在变量中:

auto search = find(o.begin(), o.end(), word);
if (search != o.end()) {
  int pos = std::distance(o.begin(), search);
  // Use pos ...
}