【发布时间】:2020-02-13 09:03:18
【问题描述】:
我的代码中有 out_of_range。我必须如何解决这个问题?有2个功能。第一个函数检查一个字符串是否是回文。第二个函数必须从向量中找到回文并将其复制到一个新的向量中,该向量是一个返回值。
#include "pch.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
bool IsPalindrom(string a)
{
string b = a;
reverse(a.begin(), a.end());
if (b == a)
{
cout << "success " << endl;
return true;
}
else {
cout << "error";
return false;
}
}
vector<string> PalindromFilter(vector<string> words, int minLength)
{
vector<string> pol;
for (int i = 0; i <= words.size(); ++i)
{
if (IsPalindrom(words[i]) && words[i].size() > minLength)
{
pol.at(i) = words.at(i);
}
}
return pol;
}
int main()
{
vector<string> a = { "ama", "madam", "safg", "arnold", "dad", "dd" };
PalindromFilter(a, 2);
}
【问题讨论】:
-
std::vector<std::string> pol是一个零长度向量。显然,任何使用at方法的索引都会引发out_of_range错误。 -
旁白:如果你使用
rbegin()和rend()成员,你不要复制字符串:bool IsPalindrome(string a) { return std::equal(a.begin(), a.end(), a.rbegin(), a.rend()); } -
旁白2:
for (string word : words)
标签: c++ pointers stdvector palindrome indexoutofrangeexception