separate vector

how do i separate my vector

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  #include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm> 
#include <ctime> 
using namespace std;


int main()
{
	srand(unsigned(std::time(0)));
	vector<int> vi;
	int n = 20;
	for (int i = 1; i < n; i++)
	{
		vi.push_back(i);
	}
	random_shuffle(vi.begin(), vi.end());
	for (vector<int>::iterator it = vi.begin(); it != vi.end(); ++it)
	cout << *it << ", ";
	


	cout << "Bye..." << endl;
	return 0;
}


output:
8, 5, 19, 4, 14, 20, 13, 3, 10, 2, 6, 9, 11, 7, 16, 12, 17, 18, 1, 15,
Bye...

I'm trying to have a output like this

8, 5, 19, 4, 14, 20, 13, 3, 10, 2, 6, 9, 11, 7, 16, 12, 17, 18, 1, 15
Bye...

I can't get rip of the , at the end of the last number
for(int count = 0; count < vi.size(); count++)
if(count == vi.size()-1)
cout << vi[count]; //possible add endl here?
else
cout << vi[count] << ", ";
Last edited on
tys, i got it
You are already using std::vector's iterators to loop the output, use the loop iterator you created:
19
20
21
22
23
24
25
26
27
28
29
30
   // use std::vector's const iterators to prevent the vector from being accidentally altered
   for (auto it = vi.cbegin(); it != vi.cend(); ++it)
   {
      std::cout << *it;

      if ((it + 1) != vi.cend())
      {
         std::cout << ", ";
      }
   }

   std::cout << "\n\nBye...\n";
17, 1, 12, 8, 20, 2, 7, 9, 15, 11, 19, 5, 16, 10, 6, 13, 14, 3, 18, 4

Bye...
Topic archived. No new replies allowed.