李锦弦 2015-05-18 07:39 采纳率: 100%
浏览 1561
已采纳

vector利用自己定义的类型出错,其解答

#include
#include
using namespace std;
class Node
{
public:
Node();
void SetX(int);图片说明
int GetX();
private:
int x;
};

Node::Node()
{
x = 0;
}
int Node::GetX()
{
return x;
}
void Node::SetX(int i)
{
x = i;
}

class test
{
public:
void Add(Node*);
vector GetNode();
private:
vector m_node;
};

void test::Add(Node* node)
{
m_node.push_back(node);
}
vector test::GetNode()
{
return m_node;
}

int main()
{
test tes;
for (int i = 0; i < 10; i++)
{
Node* node = new Node;
tes.Add(node);
}

vector<Node*>::iterator iter = tes.GetNode().begin();
for (; iter != tes.GetNode().end(); iter++)
{
    cout << (*iter)->GetX() << endl;
}

}

  • 写回答

4条回答 默认 最新

  • accsoar 2015-05-18 08:46
    关注

    你刚开始学吧,好好看看vector的用法

     class Node
    {
    public:
        Node();
        void SetX(int);
            int GetX();
    private:
        int x;
    };
    Node::Node()
    {
        x = 0;
    }
    int Node::GetX()
    {
        return x;
    }
    void Node::SetX(int i)
    {
        x = i;
    }
    class test
    {
    public:
        void Add(Node* node);
        vector<Node*>* GetNode();
    private:
        vector<Node*> m_node;
    };
    
    void test::Add(Node* node)
    {
        m_node.push_back(node);
    }
    
    vector<Node*>* test::GetNode()
    {
        return &m_node;
    }
    
    int main()
    {
        test tes;
        for (int i = 0; i < 10; i++)
        {
            Node* node = new Node;
            node->SetX(i);
            tes.Add(node);
        }
    
        vector<Node*>::iterator iter = tes.GetNode()->begin();
        for (; iter != tes.GetNode()->end(); iter++)
        {
            cout << (*iter)->GetX() << endl;
        }
    
        //最后释放node
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常