嘿,我正在编写一个需要两个 std::vector<std::string>
的函数并返回第三个 std::vector<std::string>
.
该函数将对两个 vector 一起进行编码并创建第三个 vector 。
我目前正在调试它以找出它为什么不起作用,并且我不断收到:vector subscript out of range
.据我所知,它在这一行崩溃了:
if (file2[i].size() < file1[i].size())
我可以使用 size()
吗?获取元素的大小 i
?
std::vector<std::string> Encode(std::vector<std::string> &file1,
std::vector<std::string> &file2)
{
std::vector<std::string> file3;
std::string temp;
for (unsigned int i = 0; i < file1.size(); i++) {
for (unsigned int x = 0; x < file1[i].size(); x++) {
if (file2[i].size() < file1[i].size()) {
for (unsigned int t = 0; t < file2[i].size(); t++) {
file3[i][x] = (int)file1[i][x] + (int)file2[i][t];
}
} else if (file2[i].size() > file1[i].size()) {
file3[i][x] = (int)file1[i][x] + (int)file2[i][x];
}
if (file3[i][x] > 126) {
file3[i][x] = file3[i][x] % 127;
} else {
file3[i][x] = file3[i][x] + 32;
}
}
}
return file3;
}
知道这里发生了什么吗?
最佳答案
我非常倾向于通过因式分解来简化。最底层是一个 combine
函数,将两个 char
合并为一个:
char combine(char a, char b)
{
char result = a+b;
if (result > 126)
return result % 127;
return result+32;
}
下一个级别是遍历两个可能不同大小的字符串中的每个字母。该算法通过较短的字符串“回收”来处理不同长度的字符串。
std::string mix(const std::string &first, const std::string &second)
{
unsigned len1 = first.length();
unsigned len2 = second.length();
if (len1 < len2)
return mix(second, first);
std::string result;
// if the strings are of different lengths, first is now the longer
unsigned j=0;
for (unsigned i=0; i < len1; ++i, ++j) {
if (j >= len2)
j = 0;
result.push_back(combine(first[i], second[j]));
}
return result;
}
最后,string
的vector
的组合就简单多了:
std::vector<std::string> Encode(const std::vector<std::string> &file1,
const std::vector<std::string> &file2)
{
std::vector<std::string> file3;
assert(file1.size() == file2.size());
for (unsigned int i = 0; i < file1.size(); i++) {
file3.push_back(mix(file1[i], file2[i]));
}
return file3;
}
请注意,代码当前使用 assert
来确保两个 vector
的长度相同,但这可能是人为的约束。真正的代码应该要么确保它们的长度相同,要么采取其他措施来处理这种情况。由于不清楚你的函数打算做什么,我把它留给你来决定如何处理它,但是用 assert
作为占位符来提醒你它确实需要解决.
最后,一些使用 C++11 的驱动程序代码:
int main()
{
std::vector<std::string> english{"one", "two", "three", "four"};
std::vector<std::string> spanish{"uno", "dos", "tres", "cuatro"};
auto result = Encode(english, spanish);
std::copy(result.begin(), result.end(),
std::ostream_iterator<std::string>(std::cout, " "));
}
请注意,我还使用 push_back
附加到字符串的末尾,并使用 const
声明传递的字符串。
关于c++ - 在函数中编码两个 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24844578/