Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,884 questions

51,810 answers

573 users

How to create a vector containing all elements that are included in other two vectors in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <set>

// Function that returns the union of two integer vectors without duplicates
std::vector<int> getElements(const std::vector<int>& vec1, const std::vector<int>& vec2) {
    std::set<int> elementsSet;
    elementsSet.insert(vec1.begin(), vec1.end());
    elementsSet.insert(vec2.begin(), vec2.end());
    
    return std::vector<int>(elementsSet.begin(), elementsSet.end());
}

int main() {
    std::vector<int> vec1 = {1, 1, 2, 3, 4, 4, 5};
    std::vector<int> vec2 = {4, 5, 3, 3, 6, 7, 8, 8, 8};

    std::vector<int> result = getElements(vec1, vec2);

    std::cout << "Result: ";
    for (int elem : result) {
        std::cout << elem << " ";
    }
}

 
 
/*
run:

Result: 1 2 3 4 5 6 7 8 
 
*/

 



answered Jul 6, 2025 by avibootz
edited Jul 6, 2025 by avibootz
...