[英]Putting the last integer on a new line when outputting integers in ascending order
In the code below, I am trying to output the integers in ascending order.在下面的代码中,我试图按升序输出整数。 It works, however I want the final integer to be put on a newline (final integer only- not the other integers).它有效,但是我希望将最终整数放在换行符上(仅限最终整数 - 而不是其他整数)。 I have tried我试过了
cout << myVec[i] << " "; endl
and...和...
cout << myVec[i] << endl;
but, both do not give the output I am looking for (these affect the other integers which is not what I want.但是,两者都没有给出我正在寻找的输出(这些会影响其他不是我想要的整数。
#include <iostream>
#include <vector>
using namespace std;
void SortVector(vector<int>& myVec)
{
int n = myVec.size();
int i, j;
for (i = 0; i < n - 1; i++)
for (j = 0; j < n - i - 1; j++)
if (myVec[j] > myVec[j + 1])
{
int temp = myVec[j];
myVec[j] = myVec[j + 1];
myVec[j + 1] = temp;
}
}
int main()
{
int i, n, value;
cin >> n;
vector<int> myVec;
for (i = 0; i < n; i++)
{
cin >> value;
myVec.push_back(value);
}
SortVector(myVec);
for (i = 0; i < n; i++)
cout << myVec[i] << " ";
return 0;
}
Print all but the last element on one line:在一行上打印除最后一个元素之外的所有元素:
for (i = 0; i < n-1; i++) // notice n-1
std::cout << myVec[i] << ' ';
std::cout << '\n';
Then you can print the last afterwards:然后你可以打印最后一个:
if(myVec.size())
std::cout << myVec.back() << '\n';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.