C++三维向量元素比较与分形噪声图形合并实现问题
分形噪声图形合并实现方案
需求描述
我需要处理一个三维向量结构:父向量allGraphVec包含多个存储x、y坐标的子向量,每个子向量的元素是sf::Vector2f类型的坐标对。具体要求:
- 若任意子向量中的坐标对与其他子向量的坐标对x值相等,则将二者的y值相加;
- 若坐标对无匹配x值,使用已有函数将其y值添加到下一个子向量的对应点;
最终要得到单个子向量用于分形噪声的渲染,目前已生成多组图形但不知如何合并。
现有代码
void Noise() { std::vector<sf::Vector2f> finalGraph; std::vector<sf::Vector2f> singleNoise; std::vector<std::vector<sf::Vector2f>> allGraphVec; float persistance = 0.5; int nOOPM1 = 4; //generates the graphs to be added for (int i = 0; i < nOOPM1; i++) { float frequency = pow(2, i); float amplitude = pow(persistance, i); singleNoise = this->generateNoise(frequency, 300 * amplitude); allGraphVec.emplace_back(singleNoise); } //Do what I described above over here //This is pseudoCode I have no idea what Im doing here for(auto &v : allGraphVec){ if(v1 has a v2 == to another v1's v2){ add the v2 take the added value and put it in finalgraph } } //this function just draws a line between each point in the graph, making it a graph not a series of points for (std::vector<sf::Vector2f>& v : allGraphVec) { v = this->interpolateNoise(v, 3, 1000); } //this will be rendered this->graphToBeRendered = finalGraph };
解决方案
核心思路是利用**有序哈希表(std::map)**统一统计所有x坐标对应的y值总和,同时调整代码顺序,先完成插值再合并(确保所有子向量的x轴点统一,符合分形噪声叠加逻辑)。
修改后的完整代码
void Noise() { std::vector<sf::Vector2f> finalGraph; std::vector<sf::Vector2f> singleNoise; std::vector<std::vector<sf::Vector2f>> allGraphVec; float persistance = 0.5; int nOOPM1 = 4; // 生成多组噪声图形 for (int i = 0; i < nOOPM1; i++) { float frequency = pow(2, i); float amplitude = pow(persistance, i); singleNoise = this->generateNoise(frequency, 300 * amplitude); allGraphVec.emplace_back(singleNoise); } // 先对所有噪声图形插值,确保x轴点连续且统一 for (std::vector<sf::Vector2f>& v : allGraphVec) { v = this->interpolateNoise(v, 3, 1000); } // 用map统计每个x对应的y值总和,自动按x排序 std::map<float, float> xToYSum; for (const auto& graph : allGraphVec) { for (const auto& point : graph) { xToYSum[point.x] += point.y; } } // 将统计结果转换为渲染用的向量 for (const auto& pair : xToYSum) { finalGraph.emplace_back(sf::Vector2f(pair.first, pair.second)); } // 赋值给待渲染图形 this->graphToBeRendered = finalGraph; };
关键说明
- 先插值再合并:
interpolateNoise生成1000个均匀分布的x点,确保所有子向量的x值完全匹配,直接累加y值即可,无需处理“无匹配x值”的情况,完美契合分形噪声的叠加逻辑; - std::map的作用:自动按x值从小到大排序,生成的
finalGraph是有序的,渲染折线时不会出现点乱序的问题; - 若
interpolateNoise无法生成统一x点,可先收集所有子向量的x值集合,用你的已有函数补全每个子向量的缺失x点,再用map累加y值。
内容的提问来源于stack exchange,提问作者DGYLLEANN
相关产品推荐
相关产品推荐

