【问题标题】:Problem Modifying Eigen Members of a C++ Structure修改 C++ 结构的特征成员的问题
【发布时间】:2020-05-16 17:15:27
【问题描述】:

我有以下 C++ 结构

struct voxel {
    const std::vector<Eigen::ArrayXf>& getVoltage() const { return m_voltage; }
    const std::vector<int>& getChannelIndex() const { return m_channelIndex; }
    float getx() { return m_x; }
    float gety() { return m_y; }
    float getz() { return m_z; }

    void appendVoltage(Eigen::ArrayXf v) { m_voltage.push_back(v); }
    void appendChannelIndex(int c) { m_channelIndex.push_back(c); }
    void setPosition(float x, float y, float z) { m_x = x; m_y = y; m_z = z; }
    void change(int c) { m_voltage.at(c)(0) = -100; std::cout << m_voltage.at(c) << "\n"; }

private:
    std::vector<Eigen::ArrayXf> m_voltage;
    std::vector<int> m_channelIndex;
    float m_x;
    float m_y;
    float m_z;
};

上面结构的数组用在下面的类中

class voxelBuffer {
public:
    std::vector<voxel> voxels;
    voxel getVoxel(ssize_t voxelId) { return voxels.at(voxelId); };
    const std::vector<Eigen::ArrayXf>& getVoltage2(ssize_t voxelId) const { return voxels.at(voxelId).getVoltage(); };
    ssize_t getNumVoxels() { return voxels.size(); }    
};

举个例子:

voxel vx1;
vx1.setPosition(1.1, 2.1, 3.1);
vx1.appendChannelIndex(1);
vx1.appendVoltage(Eigen::ArrayXf::LinSpaced(10, 0.0, 10 - 1.0));
vx1.appendChannelIndex(2);
vx1.appendVoltage(Eigen::ArrayXf::LinSpaced(20, 0.0, 20 - 1.0));
vx1.appendChannelIndex(3);
vx1.appendVoltage(Eigen::ArrayXf::LinSpaced(30, 0.0, 30 - 1.0));

voxelBuffer vxbuffer;
vxbuffer.voxels.push_back(vx1);

我尝试更改voxel的第一个数组

vxbuffer.getVoxel(0).change(0); 
std::cout << vxbuffer.getVoltage2(0).at(0) << "\n";

但是元素仍然没有被修改。有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: c++ class struct pass-by-reference eigen


    【解决方案1】:

    vxbuffer.getVoxel(0) 没有返回对容器中 voxel 的引用。您正在返回它的副本,因为您的返回类型 voxel getVoxel(ssize_t voxelId)voxel,而不是 voxel&amp;

    然后你在voxel 类型的临时对象上调用.change(0),而不是在容器中的voxel 对象上。

    【讨论】:

      猜你喜欢
      • 2012-12-12
      • 1970-01-01
      • 2011-04-18
      • 1970-01-01
      • 2018-12-18
      • 2022-01-04
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多