多维向量C++的加法
Addition of multidimensional vectors C++
尝试对三维矢量中的元素求和时有点头疼。
它适用于我目前正在编程的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。对于矢量和"数学"类型的代码,只使用数组索引表示法
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- 在C++中调整向量中的索引
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么