我正在编写一个程序,它将接收一个文本文件,从该文件的名称列表中读取,按字母顺序对这些名称进行排序,然后将排序后的列表打印出来。
这最初是我的“编程简介”类的一个项目,它使用数组,但我正在尝试重新设计它以使用向量,允许我使用任何长度的文件而不是刚性数组长度。
但是Intellisense给了我一个错误:
“std :: vector< std :: string,std :: allocator< std :: string>>”中没有合适的转换函数to“std :: vector< std :: string,std :: allocator< std :: string>> *”存在
每当我尝试将文件名传递给函数时(例如displayArray(names, nameQty)
,我都会收到names
的错误)。我很难用谷歌搜索如何将向量传递给函数,所以我认为这就是我的问题所在。完整代码粘贴在下面:
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
int readFromFile(string[], string);
void displayArray(vector<string>[], int);
void alphaSort(vector<string>[], int);
void swap(string&, string&);
int main() {
//Declare variables
string fileName;
vector<string>names(1);
int nameQty;
//Prompt for file name
cout << "Please enter the name of the file to read names from: " << endl;
cin >> fileName;
//Call function to open file and read names into a vector array. Function will return the number of names in file
nameQty = readFromFile(names, fileName);
//Display unsorted names
cout << "Unsorted names:" << endl;
displayArray(names, nameQty);
//Sort names into alphabetical order
alphaSort(names, nameQty);
//Display sorted names
cout << "Sorted names:" << endl;
displayArray(names, nameQty);
//More to come after this; program isn't done yet!
}
/*
* Function to read a list from a text file into an array.
* The array starts at size 1, then increments by 1 for each subsequent iteration
* The array then deletes the final element when there is nothing more to read
* (since the last element will be uninitialized)
*/
int readFromFile(vector<string> array, string fileName) {
ifstream inputFile;
inputFile.open(fileName);
if (!inputFile) {
cout << "Invalid file name. Please restart program and try again."
<< endl;
system("pause");
exit(EXIT_FAILURE);
}
else {
int index = 0;
while (inputFile) {
cin >> array[index];
array.push_back;
index++;
}
array.pop_back;
inputFile.close();
return (index + 1);
}
}
//Function to display list of items in array
void displayArray(vector<string> array[], int quantity) {
for (int i = 0; i < quantity; i++)
cout << array[i] << endl;
}
//Selection sort function puts array elements in alphabetical order
void alphaSort(vector<string> names[], int qty) {
for (int j = 0; j < qty - 1; j++) {
for (int i = j + 1; i < qty; i++) {
if (names[j] > names[i]) {
swap(names[j], names[i]);
}
}
}
}
//Function to swap elements a and b in array
void swap(string &a, string &b) {
string temp = a;
a = b;
b = temp;
}
请放心使用system("pause")
和using namespace std
。我知道这种做法很糟糕,但这就是我们在课堂上被要求做的事情。
答案 0 :(得分:1)
你想:
void displayArray(vector<string>& array, int quantity)
或者在这种情况下更好:
void displayArray(const vector<string>& array, int quantity)
在您的代码中,您似乎正在尝试传递一个向量数组(在C ++中这并不是那么简单,在这种情况下归结为指向向量的指针)。为避免复制,您应该使用引用。
您可能还有兴趣阅读move semantics。
另外,如评论中所述,您可能还想修复readFromFile
:
int readFromFile(vector<string>& array, string fileName)
通过将其更改为引用,该函数将修改调用者的向量,而不是创建和修改本地副本。