Reputation: 2255
I'm creating a program that puts prime numbers into a vector. I'll give an example to better demonstrate how this program should work:
User: 3
Output 3
User: 13
Ouput: 3 5 7 11 13
To put it in words, this program is adding up the prime numbers less than or equal to the input of the user. Then finally giving a bool of true or false if the actual input of the user was a prime number.
if (found)
{
vector_output.push_back(j);
}
if (number == j)
{
if (found ==false)
return false;
else
void checkprime::vector_finder()
{
for (int k=0; k < vector_output.size(); k ++)
{
cout << vector_output[k];
}
}
Unfortunately, my output is:
User 3
Output 3
User 13
Output: 3 5 5 5 7 7 7 7 7 9 11 13
How can I get it to where the vector does not duplicate numbers?
I thought something like an if statement right before the vector_output.pushback(j) such as
if (vector_output.size() != 0 && vector.output.back() != j)
vector_output.push_back(j);
would work, but it's not outputting anything with this.
Upvotes: 1
Views: 111
Reputation: 96790
You can remove the duplicates using std::unique
. For example:
std::vector<int> v{1, 2, 2, 3, 5, 9, 1};
std::sort(v.begin(), v.end());
v.erase(std::unique(v.begin(), v.end()), v.end());
Upvotes: 1