库特是空的,我不知道为什么
Cout is empty and I don't know why
从事leetcode练习,您可以在这里看到:https://leetcode.com/problems/unique-morse-morse-code-words/
我很难获得正确的答案,但是找到问题的问题更大。我正在尝试使用COUT打印我正在使用的向量以查看出了什么问题,但由于某种原因,它似乎是在cout空字符串。
这是我的代码...
#include <array>
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int uniqueMorseRepresentations(vector<string>& words) {
int num_of_uniq_words = 0;
string arr[] = {"a","b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"l", "m","n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
string maps[] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..",
"--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
vector<string> all_words_morse;
for (int i = 0; i < words.size(); i++) {
string morse;
for (int j = 0; j < words[i].length(); j++){
for(int q = 0; q < sizeof(arr)/sizeof(arr[0]); q++) {
if (arr[q] == to_string(words[i].at(j)))
morse.append(maps[q]);
}
}
//cout << morse << endl;
all_words_morse.push_back(morse);
}
vector<string> uniq_words;
for(int i = 0; i < all_words_morse.size(); i++) {
if (find(uniq_words.begin(), uniq_words.end(), all_words_morse[i]) == uniq_words.end()) //not present
uniq_words.push_back(all_words_morse[i]);
}
//printing
for (int i = 0; i < all_words_morse.size(); i++)
cout << all_words_morse[i] << " ";
cout << "n" << endl;
for (int i = 0; i < uniq_words.size(); i++)
cout << uniq_words[i] << " ";
cout << "n" << endl;
num_of_uniq_words = uniq_words.size();
return num_of_uniq_words;
}
};
以及[" gin"," zen"," gig"," msg"的测试用例输入,sdtout是..."
"
这是大约4行的空字符串,我不明白为什么。有人有任何建议还是知道我在做什么错?谢谢
问题是使用to_string
函数。它没有做您认为的事情:
std :: to_string
将数字值转换为std :: string。
您将字符传递给它,因此将char解释为数字值,即其ASCII值。例如,对于" g",您会得到'103'。
为什么arr
仅包含字符,而不是字符串而不是字符?如果是一系列字符,您就不需要to_string函数。
P.S。要在代码中找到问题,最好的方法是调试它。调试器是每个程序员都应使用的工具。所以请检查一下。
问题
函数std::to_string
不将char
作为参数,因此将其隐式转换为INT,该INT返回数字的字符串。示例: to_string('a') -> to_string(97) -> "97"
。
fix
使用std::string(1,words[i].at(j))
正确将char
转换为字符串或使用std::string
的subtr方法。
替代方法
正如托马斯·马修斯(Thomas Matthews(在评论中所建议的那样,使用std::map<char, std::string>
并创建地图以避免必须管理两个列表,转换,并使用在O(logn)
中执行查找的结构而不是O(n)
。
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 我不知道为什么这段代码会让核心被转储?
- 没有函数模板的实例与我不知道为什么的参数列表匹配
- if-else 语句仅按特定顺序工作,我不知道为什么
- DirectX 11 引擎在第三次代码改进后没有突然运行,我不知道为什么
- 函数抛出seg错误,我不知道为什么
- 我不知道为什么复制构造函数的调用在 c++ 中不稳定
- 随着时间的推移,我的程序越来越慢,我不知道为什么.内存泄漏
- "错误:在'.标记'之前出现预期的主表达式,我不知道为什么
- 我正在制作c ++代码,但发生错误我不知道为什么
- std::cout << glGetString(GL_RENDER) << std::endl;抛出错误但不GL_Renderer或GL_Verision,我不知道为什么?
- 我的Arduino串行命令行不起作用,我不知道为什么
- 我正在编写一个拆分为 3 的合并排序,我不知道为什么它不起作用
- 我不知道为什么我的矢量无法推回
- 语法检查器指出一些我不知道为什么的错误
- 我不知道为什么我的字符串无法保存值
- 编写蒙特卡洛集成程序,我不知道为什么我会收到某些错误
- 我不知道为什么会发生堆损坏(关于内存分配问题)
- 库特是空的,我不知道为什么
- C++:我需要在这里包含这个标题,我不知道为什么