c++ vector push if not exist

To push an element into a vector in C++ only if it doesn't already exist, you can follow these steps:

  1. Declare a vector to store the elements:
std::vector<int> myVector;
  1. Create a function to check if the element already exists in the vector:
bool elementExists(const std::vector<int>& vec, int element) {
    return std::find(vec.begin(), vec.end(), element) != vec.end();
}
  1. Specify the element you want to push into the vector:
int elementToPush = 42;
  1. Check if the element already exists in the vector using the elementExists function:
if (!elementExists(myVector, elementToPush)) {
    myVector.push_back(elementToPush);
}

Here's the full code:

#include <iostream>
#include <vector>
#include <algorithm>

bool elementExists(const std::vector<int>& vec, int element) {
    return std::find(vec.begin(), vec.end(), element) != vec.end();
}

int main() {
    std::vector<int> myVector;
    int elementToPush = 42;

    if (!elementExists(myVector, elementToPush)) {
        myVector.push_back(elementToPush);
    }

    // Print the vector
    for (const auto& element : myVector) {
        std::cout << element << " ";
    }

    return 0;
}

This code snippet declares a vector myVector, creates a function elementExists to check if an element already exists in the vector, specifies the element to push (elementToPush), and finally, checks if the element exists in the vector before pushing it using an if condition. The vector is then printed to verify the result.