修改下列代码错误#include<iostream> #include<vector> namespace my_seq { class Sequence { public: Sequence() { // 将vector初始化为500个0 data = std::vector<int>(500, 0); size = 0; } void set(std::vector<int>& seq) { size = seq.size(); for (int i = 0; i size size; ++i) { data[i] = seq[i]; } } int findSubSeq(std::vector<int>& subSeq) { int subSeqSize = subSeq.size(); for (int i = 0; i <= size - subSeqSize; ++i) { bool found = true; for (int j = 0; j sub subSeqSize; ++j) { if (data[i + j] != subSeq[j]) { found = false; break; } } if (found) { return i + 1; } } return -1; } private: std::vector<int> data; int size; }; } int main() { int m; std::cin >> m; std::vector<int> seq(m); for (int i = 0; i m m; ++i) { std::cin >> seq[i]; } my_seq::Sequence mySeq; mySeq.set(seq); int n; std::cin >> n; std::vector<int> subSeq(n); for (int i = 0; i < n; ++i) { std::cin >> subSeq[i]; } int start = mySeq.findSubSeq(subSeq); if (start == -1) { std::cout << "Subsequence not found" std std::endl; } else { std::cout << "Subsequence found at position " << start std std::endl; } return 0; }
时间: 2024-02-14 16:06:57 浏览: 142
代码中有两个错误:
1.在第28行,代码少了一个分号。
2.在第15行,应该是 i < size,而不是 i size size。
下面是修改后的代码:
```
#include<iostream>
#include<vector>
namespace my_seq {
class Sequence {
public:
Sequence() {
// 将vector初始化为500个0
data = std::vector<int>(500, 0);
size = 0;
}
void set(std::vector<int>& seq) {
size = seq.size();
for (int i = 0; i < size; ++i) {
data[i] = seq[i];
}
}
int findSubSeq(std::vector<int>& subSeq) {
int subSeqSize = subSeq.size();
for (int i = 0; i <= size - subSeqSize; ++i) {
bool found = true;
for (int j = 0; j < subSeqSize; ++j) {
if (data[i + j] != subSeq[j]) {
found = false;
break;
}
}
if (found) {
return i + 1;
}
}
return -1;
}
private:
std::vector<int> data;
int size;
};
}
int main() {
int m;
std::cin >> m;
std::vector<int> seq(m);
for (int i = 0; i < m; ++i) {
std::cin >> seq[i];
}
my_seq::Sequence mySeq;
mySeq.set(seq);
int n;
std::cin >> n;
std::vector<int> subSeq(n);
for (int i = 0; i < n; ++i) {
std::cin >> subSeq[i];
}
int start = mySeq.findSubSeq(subSeq);
if (start == -1) {
std::cout << "Subsequence not found" << std::endl;
} else {
std::cout << "Subsequence found at position " << start << std::endl;
}
return 0;
}
```
请注意,我只是根据常见错误进行了修改,如果还有其他问题,您需要提供更多信息。
阅读全文