【发布时间】:2015-10-07 15:32:46
【问题描述】:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <string>
using namespace std;
void alpha_sorting(vector<string>& a);
void swap_function(vector<string>& x,int& l);
string alpha_least(vector<string>& list,int& idx);
int min_word_index(string& min,vector<string>& listed);
int main(){
ifstream infile;
infile.open("words.txt");
if(!infile.is_open()){
cout << "Could not open the input file" << endl;
exit(EXIT_FAILURE);
}
vector<string> words;
string temp;
while(infile >> temp){
words.push_back(temp);
}
sort_words_alphabetically(words);
cout << "Those words in alphabetical order are " << endl;
return 0;
}
void alpha_sorting(vector<string>& a){
int index = 0;
while(index < a.size()){
swap_min_to_top(a, index);
index++;
}
for(int i = 0;i < a.size();i++){
cout << a[i] << endl;
}
}
void swap_function(vector<string>& x,int& l){
string temporary;
temporary = x[l];
wrdx[loc] = minimum_word(x, l);
int min_idx = min_word_index(x[l], x);
x[min_idx] = temporary;
}
string alpha_least(vector<string>& list,int& idx){
string temp = list[idx];
for(int i = idx;i < list.size();i++){
if(list[i] < temp){
temp = list[i];
}
}
return temp;
}
int min_word_index(string& min,vector<string>& listed){
for(int i = 0;i < listed.size();i++){
if(min == listed[i]){
return i;
}
}
return -1;
}
大家好,
简而言之,作业要求我们从文件中读取单词并按字母顺序排列它们并将它们显示到屏幕上。
该作业明确禁止使用诸如排序等 c++ 函数,并希望我们创建自己的算法来排列这个向量。
我的算法在列表中找到最小值(字母表中的那个)字符串(使用“
有人可以找出我的代码有什么问题吗?
【问题讨论】:
-
为了对向量进行排序,您可以交换元素。在您的算法中,您没有两个要交换的索引。
看起来您正在搜索中途进行交换。尝试使该函数首先搜索它想要交换的内容,然后才进行交换。 -
@dascandy 我为此创建了 swap_min_to_top 函数。有什么问题吗?
-
如果这不是作业,你试过
std::sort吗? -
@Afr0:尝试制作一个简单的程序,在包含 2 或 3 个元素的向量上以错误的顺序运行它。然后让它工作。然后,通过添加更多测试调用来扩展它。此外,使用调试器(例如,Visual Studio)查看程序的状态。
-
@dascandy,感谢您的建议,正如 theAlias 指出的那样,我有一个按时间顺序排列的错误。并进一步补充这是家庭作业的想法。这实际上是我第一年的一项任务,我做得很差,所以它总是我打算完成的事情。我还添加了一个功能,使用户可以通过字符串操作搜索在该目录中输入的任何单词。我对此只有一个问题:用于对向量进行排序和实现搜索功能的方法是否足够有效?
标签: c++ string vector alphabetical