gpt4 book ai didi

c++ - 字符 vector 的奇怪输出

转载 作者:行者123 更新时间:2023-11-27 22:35:22 25 4
gpt4 key购买 nike

背景:

这个问题来自 Daily Coding problem #29。

Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character. For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".

Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid.

尝试的解决方案:

#include <iostream>
#include <string>
#include <vector>

std::vector<char> run_length(std::string str)
{
std::vector<char> result;
if (str.empty() || str.size() == 1)
{
const char *ch = str.c_str();
result.push_back(*ch);
return result;
}

int count = 1;
for (int i = 1; i < str.size(); ++i)
{
if (str[i] == str[i - 1])
count++;
else
{
if (count > 1)
{
char ch = count;
result.push_back(ch);
}
result.push_back(str[i - 1]);
count = 1;
}
}
if (count > 1)
{
char ch = count;
result.push_back(ch);
}
result.push_back(str[str.size() - 1]);

return result;
}

int main()
{
std::string str = "AAAABBBCCAA";
auto result = run_length(str);

for (auto it : result)
std::cout << it << " ";

std::cin.get();
}

预期输出:

4A3B2C1D2A

实际输出:

 A  B  C  A  

问题:

为什么实际输出会出现这些奇怪的字符?我相信我的方法的逻辑应该可以解决问题,但是我得到了这些我以前从未见过的字符。非常感谢任何建议。

最佳答案

线

char ch = count;

不正确。

如果count 为4,则ch 被初始化为一个由整数值4 编码的字符。您需要获取表示数字的字符。您需要 '4'。您可以使用以下命令从 count 中获取数字。

char ch = '0' + count;

但是,如果 count 大于 9,那将不起作用。如果您希望 count 大于 9,则必须想出不同的策略。

关于c++ - 字符 vector 的奇怪输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55009585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com