多维向量C++的加法

Addition of multidimensional vectors C++

本文关键字:C++ 向量      更新时间:2023-10-16

尝试对三维矢量中的元素求和时有点头疼。

它适用于我目前正在编程的k均值算法;这是一个我理解的算法,可以在纸上完成,但在语法上我现在有点舌头打结。我可能会提到,这个项目是我第一次真正用C++处理复杂的容器。目前,我想为集群中的点计算新的质心,这是通过平均集群中每个坐标的位置来完成的。我的三维向量是一个簇的向量,每个簇都包含一个向量,其中包含我在该簇中坐标的向量(我希望这听起来很清楚,希望我的代码能缓解任何混乱)。我目前正在尝试使用迭代器,但我正在考虑回到int和索引,因为我对它们更熟悉,尽管我觉得我应该学习这种语法是如何工作的,因为它似乎很重要,也很强大。

我只发布我被卡住的函数和与之相关的头部部分。如果你想查看任何其他代码,我很乐意根据要求添加,但我觉得这应该足以说明我的问题。

.h file parts (public members of class):
vector< vector < vector <float> > > clusters; 
vector<vector<float> > avg;
int avgDiv;


.cpp file part with comments to help elaborate my query:
    vector<vector<vector<float> > >::iterator threeD;
    vector<vector<float> >::iterator row;
    vector<float>::iterator col;
    for (threeD = clusters.begin(); threeD != clusters.end(); threeD++) {
        for (row = threeD->begin(); row != threeD->end(); row++) {
            for(col = row->begin(); col != row->end(); col++){
             //its this code below that is causing my headache, 
             //I know that what is written isn't correct, 
             //it is there to serve as an example of what I've 
             //been trying to do to sort out my issue. 
             avg.at(row) ( = or push_back ) ((clusters.at(row).at(col)) + (clusters.at(row+1).at(col))); 
            }
            avgDiv = distance(row->begin(),row->end());
            //divide each value in avg vector by the amount of members in row, giving the new centroid for that cluster, loop forward to next cluster. this isn't a problem I should think. 
        }
    }

我的问题是编译器告诉我对"at"的调用不是成员函数。从其他问题中可以看出,这是因为我没有将正确的对象作为自变量传递,不过,我确信我想将迭代器所在的向量中的每个元素与行中的下一个元素相加。

我已经尽可能清楚地说明了这一点,请询问,我会尽可能多地补充细节以帮助您回答。我是个新手,很乐意接受批评;这只会让我成为一个更好的程序员。谢谢你抽出时间。

avg.at(index)与整数索引一起使用,它只是带有边界检查的'c'数组[index]表示法——顺便说一句,在实际代码中,您希望使用[]或禁用检查以提高速度。

row是一个迭代器,实际上它已经是avg中元素的指针,所以只需取消引用它即可获得值。

*row = value of avg at position of iterator 'row'

C++迭代器教程http://www.cprogramming.com/tutorial/stl/iterators.html

ps。对于矢量和"数学"类型的代码,只使用数组索引表示法

通常更简单