To implement the function removeDuplicateVerts in C++, which removes duplicate vertices from a std::vector<vec3f> (assuming vec3f is a 3D float vector, such as from GLM or a custom struct), you can use the following approach:
✅ Approach:
Use an unordered_map with a custom hash to map each vertex to a unique index.
Iterate through the input vector and add only unique vertices to the result.
Here's a complete implementation:
🔧 Step-by-step Implementation
cpp
#include <vector>
#include <unordered_map>
#include <glm/vec3.hpp> // Assuming vec3f is glm::vec3; replace if using another library or custom type
using vec3f = glm::vec3; // Remove or change this if you're not using GLM
// Custom hash for vec3f
struct Vec3fHash {
size_t operator()(const vec3f& v) const {
// Combine hashes of x, y, z using boost-like hash_combine
std::size_t h1 = std::hash<float>()(v.x);
std::size_t h2 = std::hash<float>()(v.y);
std::size_t h3 = std::hash<float>()(v.z);
return h1 ^ (h2 << 16) ^ (h2 >> 16) ^ h3;
}
};
// Equality comparator for vec3f
struct Vec3fEqual {
bool operator()(const vec3f& a, const vec3f& b) const {
return a.x == b.x && a.y == b.y && a.z == b.z;
}
};
// Function to remove duplicates
std::vector<vec3f> removeDuplicateVerts(const std::vector<vec3f>& verts) {
std::unordered_map<vec3f, int, Vec3fHash, Vec3fEqual> seen;
std::vector<vec3f> result;
for (const auto& v : verts) {
if (seen.find(v) == seen.end()) {
seen[v] = 1;
result.push_back(v);
}
}
return result;
}
📝 Notes:
If you're not using GLM, make sure your vec3f has public x, y, z members or adjust the hash and equality accordingly.
The Vec3fHash and Vec3fEqual functors are required because std::unordered_map needs a way to hash and compare user-defined types.
This method ensures that floating-point precision issues are avoided assuming exact matches. If you need tolerance (e.g., epsilon-based comparison), let me know and I can update the code accordingly.
Let me know if you want to also track original indices or do something like remapping indices after deduplication!