库特是空的,我不知道为什么

Cout is empty and I don't know why

本文关键字:我不知道 为什么      更新时间:2023-10-16

从事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)

<</p> <</p> <</p>