简体   繁体   中英

Problem Modifying Eigen Members of a C++ Structure

I have the following C++ structure

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;
};

An array of the above structure is used in the following class

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(); }    
};

As an example:

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);

I try to change the first array of voxel

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

But the element is still not modified. Could someone please help me with this issue?

vxbuffer.getVoxel(0) is not returning a reference to the voxel in the container. You are returning a copy of it, because your return type of voxel getVoxel(ssize_t voxelId) is voxel , not voxel& .

Then you call .change(0) on that temporary object of type voxel , not on the voxel object in the container.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM