李锦弦 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条)

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题