我的代码如下所示。单词是从两个文件中读取的,需要检查以查看两个文件中是否都出现了单词。在匹配两个单词中的第一个单词并将其添加到新向量后,我一直遇到段错误。我之前添加了打印语句,并且在遇到seg错误之前,它一直使用int n参数在循环中运行。我对C ++相当陌生,因此最好选择最基本的帮助方法。
#include <iostream>
#include <string>
#include <fstream>
#include <locale>
#include <vector>
using namespace std;
vector<string> wordOne;
vector<string> wordTwo;
fileOne.open(argv[2]);
fileTwo.open(argv[3]);
while (fileOne >> wordsFirstFile) {
wordOne.push_back(wordsFirstFile);
}
while (fileTwo >> wordsSecondFile) {
wordTwo.push_back(wordsSecondFile);
}
fileOne.close();
fileTwo.close();
int sizeOneWord = wordOne.size();
int sizeTwoWord = wordTwo.size();
vector<string> printWords;
int m = 0;
int n = 0;
for (m = 0; m <= sizeOneWord; m++) {
for (n = 0; n <= sizeTwoWord; n++) {
if (wordOne[m] == wordTwo[n]) {
printWords.push_back(wordOne[m]);
}
}
}
答案 0 :(得分:1)
假设sizeOneWord
是1。这意味着wordOne
中只有一个合法索引。但是您的循环将循环两次,一次使用m == 0
,一次使用m == 1
。因此,如果向量中只有一个元素,则您将尝试访问两个元素。您需要将两个<=
比较都更改为<
。