在将元素添加到List(C ++)时如何对元素进行排序?

时间:2016-10-14 22:15:01

标签: c++ sorting

我正在尝试对单词进行排序,因为我将它们添加到C ++中的列表中。我必须使用列表,我不能使用“sort()”函数。

我有一个带有一些单词的文本文件(每个单词都在一个新行上)。

到目前为止,我已经想出了如何收集单词并将它们添加到列表中:

fstream myfile(fileName);

if(!myfile) { // Test if file open
    cout<<"Error opening file"<< endl;
    return false;

}

while (getline(myfile, line)){ //loops through and gets sayings
    l.push_back(line);
}

这些单词只是按照它们在文件中的顺序添加。我想要做的是检查单词的第一个字母,然后将其放在列表中的适当位置,而不是仅将它们添加到列表的末尾。

提前谢谢!

更多信息:

我相信我应该使用迭代器来实现这一目标。

我知道如何使用迭代器来显示列表:

for (list<string>::iterator it=l.begin(); it != l.end(); ++it)
cout << *it << endl;

在添加值之前,如何使用它来比较值?我尝试使用迭代器来使用(*it)[0]来获取单词的第一个字母,但这不是有效的语法。

2 个答案:

答案 0 :(得分:1)

我添加了一个迭代器

std::list<string> mylist;
std::list<string>::iterator it; //now I can move through the list using this kind of like an index

for (it=mylist.begin(); it!=mylist.end(); ++it)
{
    if( line.compare(*it) >= 0) //If the line belongs before what *it is pointing to
    {
        mylist.insert(it,line);
        break;
    }
}

http://www.cplusplus.com/reference/string/string/compare/

了解更多有关string :: compare的信息

了解有关插入http://www.cplusplus.com/reference/list/list/insert/

列表的详情

答案 1 :(得分:0)

假设您可以使用std::setstd::multiset

multiset<string> l;

while (getline(myfile, line)){ //loops through and gets sayings
    l.insert(line);
}

这将添加所有单词并自动排序。 multisetset之间的主要区别在于前者允许重复,而后者不允许重复。

然后,您可以使用l循环遍历for

for(string const& s : l) {
    cout << s << endl;
}