使用引用的数组 (C++) 遍历类成员
loop through class members with a referenced array (C++)
我想遍历一组相同类型的成员。这是一个有时有效,有时无效的解决方案:
#include <iostream>
#include <vector>
class Test{
public:
Test():xmin(0),ymin(0),xmax(0),ymax(0),acs((vector<int> (&)[4])xmin){};
vector<int> xmin,ymin,xmax,ymax;
vector<int> (&acs)[4];
};
int main(){
Test t;
t.xmin.push_back(2);
cout << t.xmin.size() << "=!=" <<t.acs[0].size() << endl;
}
上面的测试代码对我有用。在一个更大的程序中,我目前没有这样做,即 t.ymin 似乎与 t.acs[1] 等不同。上述结构总体上有意义还是我应该完全不同?
提前感谢,托马斯
可以使用指向成员的指针数组。这种方式可能是最快的(似乎对你很重要),但有点晦涩难懂,你必须再次提及成员变量的列表。
#include <iostream>
#include <vector>
struct Test
{
std::vector<int> xmin,ymin,xmax,ymax;
std::vector<int>& GetByIndex(int index)
{
typedef std::vector<int> Test::*ptr_to_member; // typedef makes syntax less crazy
static const ptr_to_member pointers[4] = {
&Test::xmin, &Test::ymin, &Test::xmax, &Test::ymax
};
return this->*pointers[index];
}
};
int main(){
Test t;
t.xmin.push_back(2);
std::cout << t.xmin.size() << "=!=" << t.GetByIndex(0).size() << 'n';
}
如果你不需要速度,一个非常简单的解决方案涉及一个开关:
std::vector<int>& GetByIndex(int index)
{
switch (index) {
case 0: return xmin;
case 1: return ymin;
case 2: return xmax;
case 3: return ymax;
default: abort();
}
}
这是
非常糟糕的做法。特别是,您依赖于填充细节。无法保证编译器将在中间没有任何填充的情况下布局数据成员。如果你的意思是数组,请使用数组。我的 2c...
Mike Seymour - 绝对正确 - 你的解决方案很危险。
尝试注入以下内容:
class Test
{
struct AllArrays
{
vector<int> * vec1, .... * vecN;
};
union
{
AllArrays _as_fields;
vector<int> * _as_Array[];
} _allTogether;
};
您需要为此编写一点点长限定符的有效负载:
Test t;
t._allTogether._as_fields.vec1
相关文章:
- 有什么方法可以遍历结构吗
- 在循环中按顺序遍历成员变量
- 遍历模板参数
- 在遍历处理程序的向量时注册和注销处理程序
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 遍历并行数组以确定C++中的最大数字
- 遍历顺序由 std::文件系统directory_iterator给出
- 遍历链表时的无限循环
- 遍历unordered_map向量
- 从预序遍历构造 bst 的 c++ 和 python 解决方案之间的区别
- C++声明双链表,使用两个 for 循环双向遍历列表并打印
- Rapidjson 遍历并获取复杂 JSON 对象成员的值
- 在使用 In Order 遍历成员函数时引发异常(堆栈溢出)时出现问题
- 如何调用遍历类层次结构的成员函数
- 是否可以在 constexpr 函数中遍历枚举成员,因此值为 constexpr
- 如何遍历类的实例集合并访问其模板成员
- 在向量中遍历结构成员时出错
- 遍历对类成员的引用,简单且最好是可重用的
- 使用引用的数组 (C++) 遍历类成员
- C++:遍历对象的所有成员?