在不知道输入大小的情况下对字符串向量 c++ 进行排序

Sorting a vector of strings c++ without knowing the size of the input

我在对字符串向量进行排序时遇到问题。我不应该询问字符串的数量(向量的大小),输入应该只包含应该排序的字符串。 为了找到向量的大小以便对其进行排序,我尝试了这种方法,但它不起作用:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

bool sortfunc(string i , string j)
{
    return (i < j);
}


int main()
{
    vector<string>s;
    string str;
    int count = 0;
    do
    {
        cin >> str;
        s.push_back(str);
        count++;
    }
    while (str);
    sort(s.begin(), s.begin() + count, sortfunc);
    for (int i = 0; i < count; i++)
        cout << s[i] << endl;
}

你的循环条件没有任何意义。 str 不可转换为 bool。您应该改为这样构造它:

while (cin >> str)
{
    s.push_back(str);
    count++;
}

否则,您的代码可以正常工作。如果要避免保留计数器变量,可以使用 s.end() 而不是 s.begin() + count。最后,您不需要提供自定义比较器,默认情况下它已经使用 operator<

sort(s.begin(), s.end());