C++ 我怎样才能到达cout<<&引用;已排序:“;;C+;中没有输入数字时+;

C++ 我怎样才能到达cout<<&引用;已排序:“;;C+;中没有输入数字时+;,c++,C++,我试图写一个代码来对整数向量进行排序。我的代码已经完成,并且可以正常工作。但它只是不能输出“排序:”当输入没有数字。这是我的密码: #include <iostream> #include <string> #include <vector> #include <cstdlib> using namespace std; /* sort function */ void sort(vector<int>& v) {

我试图写一个代码来对整数向量进行排序。我的代码已经完成,并且可以正常工作。但它只是不能输出“排序:”当输入没有数字。这是我的密码:

#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>

using namespace std;

/* sort function */
void sort(vector<int>& v)
{
    for (int inc1 = 0; inc1 < v.size() - 1; ++inc1)
    {
        int minimum = inc1;

        for (int inc2 = inc1; inc2 < v.size(); ++inc2)
        {
            if (v[inc2] < v[minimum])
            {
                minimum = inc2;
            }
        }

        if (minimum != inc1)
        {
            int temporary = v[minimum];
            v[minimum] = v[inc1];
            v[inc1] = temporary;
        }

        if (v.empty())
        {
          return;
        }
    }
}

/* display function */
void display(vector<int> v)
{
    for (int inc1 = 0; inc1 < v.size(); ++inc1)
    {
        cout << v[inc1];
        if (inc1 != v.size() - 1)
        {
            cout << ", ";
        }
    }

    cout << endl;
}

/* main function */

int main()
{
    /* getting inputs */
    cout << "Enter integers (one on each line, entering an empty line quits):" << endl;
    vector<int> v;
    string myString;

    while (getline(cin, myString))
    {
        /* if encounters a empty line, prints the output */
        if (myString.length() == 0)
        {
            break;
        }
        /* if not add values to the vector */
        else
        {
            v.push_back(atoi(myString.c_str()));
        }
    }

    cout << "Sorted: ";

    /* function call to sort */
    sort(v);
    /* function call to display */
    display(v);
    getchar();

    return 0;
}
#包括
#包括
#包括
#包括
使用名称空间std;
/*排序函数*/
无效排序(矢量和v)
{
对于(int inc1=0;inc1cout这是因为您的代码中有未定义的行为。在
sort
函数中,您从0迭代到
size()-1
,并且由于
size()返回的值
无符号向量为空时,32位系统上的值变为
0xffffffff
,64位系统上的值变为
0xffffffffff

void sort(vector<int>& v)
{
    if (v.empty())
    {
        return;
    }

    // ... other code here ...
}
要绕过此问题,请检查向量是否为空

void sort(vector<int>& v)
{
    if (v.empty())
    {
        return;
    }

    // ... other code here ...
}
void排序(向量&v)
{
if(v.empty())
{
返回;
}
//…这里还有其他代码。。。
}

一个建议使用
stoi
而不是
atoi
@user1336087:有什么区别吗?给你:在原始问题得到回答后,请不要更改你的问题。这会使现有答案无效。如果你有其他问题,请发布另一个问题。我如何删除“排序”后的空格:如果没有输入号码,请使用
if
语句。