我遇到了一个奇怪的问题。我试图用一个函数填充一个向量,然后用另一个函数输出它。即使在调用函数后,向量也显示为空,我相信它正确填充它。到目前为止,这是我的代码。结果是
“输入输入文件名in.txt 在向量中搜索 抛出'std :: out_of_range'实例后调用终止 what():vector :: _ M_range_check 中止(核心倾倒) “
#include <iostream>
#include <cassert>
#include<vector>
#include "ArrayUtilities.h"
using namespace std;
void fillArray(istream& io, std::vector<int> a, int& actualSize)
{
int temp,i=0;
io>>temp;
while (temp!=-999)
{
a.push_back(temp);
io>>temp;
i++;
}
actualSize=i;
}
void outputArray(ostream& os,
std::vector<int> a,
const int actualSize,
const string& info )
{
os<<info<<"\n";
for (int w=0;w<actualSize;++w)
{
os<< a.at(w)<<" ";
}
os<<"\n";
}
int main() {
int actualSize;
string fileName;
string info;
std::vector<int> a;
cout << "Enter the input file name ";
cin >> fileName;
ifstream inData;
ofstream outData;
inData.open(fileName.c_str());
outData.open("out.txt");
int searchItem;
inData>>info;
inData>>searchItem;
fillArray (inData, a, actualSize);
cout <<"Search in vector\n";
outData<<"Search in vector\n";
outputArray(outData, a, actualSize, info);
outputArray(cout, a, actualSize, info);
//sequential search
int position;
position=seqSearch(a,actualSize,searchItem);
if (position > 0)
{
cout << "Sequential Search: SearchItem "
<< searchItem
<< " is on position "
<< position
<< "\n";
outData << "Sequential Search: SearchItem "
<< searchItem
<< " is on position "
<< position
<< "\n";
}
else
{
cout << "Sequential Search: SearchItem "
<< searchItem
<< " is not in the list\n";
outData << "Sequential Search: SearchItem "
<< searchItem
<< " is not in the list\n";
}
感谢您的帮助
答案 0 :(得分:3)
您的函数具有向量的本地副本。它不会影响作为参数传递的向量。您可以通过传递对vector:
的引用来解决此问题void fillArray(istream& io, std::vector<int>& a, int& actualSize)
// ^
答案 1 :(得分:0)
juanchopanza在您的代码中显示了错误。 我会推荐一种不同的风格。
将fillArray更改为:
std::vector<int> fillArray(istream& io)
{
std::vector<int> response;
int temp;
io>>temp;
while (temp!=-999) {
response.push_back(temp);
io>>temp;
}
return response;
}
在main中使用:
int main()
{
int actualSize;
string fileName;
string info;
std::vector<int> a;
cout << "Enter the input file name ";
cin >> fileName;
ifstream inData;
ofstream outData;
inData.open(fileName.c_str());
outData.open("out.txt");
int searchItem;
inData>>info;
inData>>searchItem;
a = fillArray(inData);
// If you really like actualSize add
actualSize = a.size();
cout <<"Search in vector\n";
outData<<"Search in vector\n";
outputArray(outData, a, a.size(), info);
...
}
Natuarally我发现它更容易阅读。 根据{{3}}的演讲更容易优化。