【发布时间】:2014-09-10 17:55:56
【问题描述】:
嘿,我正在编写一个函数,它接受两个 std::vector<std::string> 并返回第三个 std::vector<std::string>。
该函数会将两个向量编码在一起并创建第三个向量。
我目前正在调试它以找出它不起作用的原因,并且我不断收到: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;
}
知道这里发生了什么吗?
【问题讨论】:
-
首先猜测,
vectorfile2 中的字符串比vectorfile1 中的字符串少。您只检查文件 1 的边界,而不检查文件 2。使用std::vector::at运算符更安全。它会抛出一个越界异常。 -
如果
file2的元素较少,那么一旦外循环到达file2的末尾,file1、file2[i]就会越界。 -
知道如何让它循环回到起点吗?
-
我希望它们迭代到 file1 的大小,因为如果文件 2 比文件 1 的大小短,我希望文件 2 循环回到开头。
-
使用单独的计数器或使用模运算符。