How to check whether a vector contains unique values in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
 
bool hasUniqueValues(const std::vector<int>& vec) {
    for (size_t i = 0; i < vec.size(); i++) {
        for (size_t j = i + 1; j < vec.size(); ++j) {
            if (vec[i] == vec[j]) {
                return false; // Duplicate found
            }
        }
    }
    return true; // All values are unique
}
 
int main() {
    std::vector<int> vec = {1, 8, 9, 0, 3, 4, 6};
 
    if (hasUniqueValues(vec)) {
        std::cout << "The vector contains unique values.\n";
    } else {
        std::cout << "The vector contains duplicates.\n";
    }
 
    return 0;
}
 
 
 
/*
run:
 
The vector contains unique values.
 
*/

 



answered Mar 28, 2025 by avibootz
edited Mar 28, 2025 by avibootz
...