在vs2022中编辑了一小段代码。编译后运行,输入一个词后回车就提示vector subscript out of range。代码如下所示。请各位达人多多指教。应该做何修改。
word.h
#pragma once
#ifndef a_word
#define a_word
#include
#include
#include
using std::vector;
using std::istream;
using std::string;
using std::cin;
using std::cout;
using std::endl;
istream& word(istream&, vector&, vector<int>&) ;
#endif
word.cpp
#include"word.h"
istream& word(istream& is, vector<string>& wd, vector<int>& sums) {
string s;
while (cin >> s) {
bool flag = false;
for (vector<string>::size_type i = 0; i <= wd.size(); ++i) {
if (s == wd[i]) {
flag = true;
sums.push_back(i);
break;
}
}
if (flag==false) {
wd.push_back(s);
sums.push_back(1);
}
}
return is;
}
main
#include"word.h"
int main() {
vector wd1;
vector<int> sums1;
word(cin, wd1, sums1);
if (wd1.size() == 0) {
cout << "向量为空。";
}else
{
cout << "一共有" << wd1.size() << "个单词。" << endl;
}
for (vector::size_type i = 0; i != wd1.size(); ++i) {
cout << wd1[i] << "出现" << sums1[i] << "次" << endl;
}
return 0;
}
i <= wd.size()
改为
i < wd.size()
vector <Girl> girls;
for (unsigned int g = 0; g < girls.size(); g++) {
girls[g]...
}
for (unsigned int b = 0; b < boys.size(); b++) {
cout << boys[b] << " 的配对女士有:" << endl;
for (unsigned int g = 0; g < girls.size(); g++) {
if (boys[b].satisfied(girls[g]) == true &&
girls[g].satisfied(boys[b]) == true) {//注意调用的是否是函数以及函数是否含参以及含参顺序
//cout << boys[b].getName() << "<-->" << girls[g].getName() << endl;如果只打印姓名,可能有重名,无法确定实际是哪位
//因为database与Boy和Girl类不存在继承关系,所以只能通过对象调用public方法
cout << girls[g] ;
}
}
cout << endl;//一位男士的所有配对结束后空一行
}