简体   繁体   English

按升序输出整数时将最后一个整数放在新行上

[英]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.

相关问题 使用C ++,当行中的最后一个整数为0时,如何检测到fgets整数字符串的末尾? - How to detect you've reached the end of a fgets string of integers, when 0 is the last integer in the line, using c++? C++ 的三个整数升序 - Ascending order with three integers for C++ 为什么我的重载&lt;&lt;运算符不输出最后一行? - Why is my overloaded << operator not outputting the last line? 输出整数时,C ++程序异常退出 - C++ program exits abnormally when outputting integers 扫描的测试文件的最后一个字符是在线输出它实际上没有打开 - Very last character of scanned testfile is outputting on line it is not actually on C ++ ofstream仅输出来自ifstream的最后一行数据 - C++ ofstream only outputting last line of data from ifstream output 用户输入组中按升序排列的重复整数的程序不打印数组的内容 - Program to output repeated integers from user-inputted group in ascending order is not printing contents of array 如何获取C ++中用逗号分隔的整数序列的最后一个整数? - How to get the last integer of sequence of integers separated by commas in C++? C ++将整数节点按升序插入模板化的单链接列表类中-家庭作业 - C++ Insert integer nodes into a templated singly linked list class in ascending order - Homework 以升序排列数组 - arranging array in ascending order
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM