Passing vector to a function

Write a program with a function to fill a vector with 100 random numbers between 1 and 500. Then pass the vector to a function that will sort it (sort(V.begin(),V.end());) You will need to #include <algorithm>). Then pass it to a function that will *remove all duplicates. Then to a function which will display the vector with 10 numbers on a line:
*Hint – When you find a duplicate, start there and move each element back one (V[k] = V[k+1] then remove the last element with pop_back.

I got it to the part where it said include <algorithm>.... than my question is
"function that will *remove all duplicate"
1. Is this question ask for a fuction?
if so, how do I pass vector to void function ?
2. how do i print 10 number per line?
3. *remove all duplicated is this pointer????
4. number.pop_back(); isn't this only erase last one ?
This is what I have so far...


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <vector>
#include <algorithm>
#include <time.h>
#include <stdlib.h>
using namespace std;

int main()
{
	srand(time(0));
	vector <int> number; 
	//get random number address 0 to 99 = 100 numbers
	for (int i = 0; i < 100; i++)
	{
		int a = rand() % 500 + 1;
		// put random number in each vector
		number.push_back(a);
	}
	//puts in order to lowest to highest
	sort(number.begin(), number.end());
	return 0;
}



Last edited on
1. Is this question ask for a function? if so, how do I pass vector to void function ?

The hint makes it sound like you are supposed to write the function yourself, and not use something ready to use like std::unique. When you pass the vector to the function you should pass it by reference so that the function modifies the original vector and not just a copy of it.
1
2
3
4
void foo(vector<int>& vec) // The & makes so that the vector is passed by reference
{
	// do somthing with vec ...
}

1
2
3
// You pass a vector the same way as any other variable
vector<int> v;
foo(v);


2. how do i print 10 number per line?

Output a newline character '\n' (or use std::endl) after each tenth element you output.

3. *remove all duplicated is this pointer????

Eh, no .... I'm not sure I understand. I don't really see where you have to use a pointer in this program.

4. number.pop_back(); isn't this only erase last one ?

Yes.
Last edited on
Topic archived. No new replies allowed.