Darren Pan Darren Pan - 3 months ago 14
C++ Question

How can I reach cout << "Sorted:"; when there are no input numbers in C++

I am trying to write a code to sort a vector of integers. My code is completed, and it works. But it just can't output "Sorted:" when input no number. Here is my code:

#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;
}


Any help is appreciated! Thank you!

Answer

This is because you have undefined behavior in your code. In your sort function you iterate from 0 to size() - 1 and since the value returned by size() is unsigned the value becomes 0xffffffff on 32 bit systems and 0xffffffffffffffff on 64 bit systems when the vector is empty.

To get around this check the vector to see if it is empty.

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

    // ... other code here ...
}
Comments