C++词表;在矢量/地图中找到完整的描述
C++ Wordlist; find a whole describtion in vector/map
如果你创建一个单词列表,我正在制作一个代码。它包含一个"单词"和一个"描述"。单词和描述有自己的向量。我也在使用地图来尝试同样的方法。
该程序进展顺利,直到我尝试查找单词为止。该程序只会从描述中获取最后一个词。有没有办法将整个句子变成一个向量?
这是我如何写下描述的代码。整个程序代码真的很长,所以我只提到重要的东西:
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 ...
}
相关文章:
- 为什么不;名字在地图上是按顺序排列的吗
- 基于多个条件处理地图中的所有元素
- 使用VerQueryValue检索应用程序的文件描述
- 在C++中将矢量转换为嵌套地图
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 如何在C/C++中用FD_set Unix设置套接字文件描述符
- PC中的程序和PHONE中的本机描述应用程序之间的数据连接
- 替换基于地图的所有引用
- 如何区分地图中的 0 和 false?
- 从 Boost ASIO 获取 epoll 描述符 io_service对象
- 地图计数确实很重要,或者只是检查是否存在
- 如何从地图中删除矢量对象
- 是否有任何C++功能可以对地图进行排序?
- 如何使用 std::variant 打印地图键/值?
- 从矢量或地图中删除共享指针
- 在 c++ 中,有一种方法可以创建一个包含地图作为值的树状地图?
- 无限嵌套具有变体的地图
- C Boost ::如何从顶点描述符创建地图
- 提升::精神.将(名称)(描述)文本解析到地图
- C++词表;在矢量/地图中找到完整的描述