使用引用的数组 (C++) 遍历类成员

loop through class members with a referenced array (C++)

本文关键字:遍历 成员 C++ 引用 数组      更新时间:2023-10-16

我想遍历一组相同类型的成员。这是一个有时有效,有时无效的解决方案:

#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