0
 class Way {
private:
    std::vector<Node> nodesCollection; 
public:
    Way();
    Way(const Way& orig);
    virtual ~Way();

    void SetNodesCollection(std::vector<Node> nodesCollection);
    std::vector<Node> GetNodesCollection() const;
};

I added vector as a property and I'm accessing that vector from following class and adding items.

Way wayNode;

 for (; WayIter!=wayNodes.end(); ++WayIter)
{
    const JSONNode& arrayNode = *WayIter;
    if (arrayNode.find("ref") != arrayNode.end() )
    {
        std::string id = arrayNode.find("ref")->as_string();

        if(nodesMap.find(id) != nodesMap.end())
        {
            wayNode.GetNodesCollection().push_back(nodesMap.find(id)->second);
        }
    }
}

but items are not adding to "nodesCollection". its count is zero. that adding object is not null.

I need some help to sort out this. I'm new to c++.

Thanks in advance.

JanithOCoder
  • 39
  • 1
  • 7

1 Answers1

1

You need to read about pass by value vs pass by reference. GetNodesCollection is returning a brand new copy of the vector. Then you add your nodes to this new copy, instead of to the original.

Well, maybe it is more return by value vs return by reference. Anyway the point is that you are getting a brand new copy instead of a reference to the original vector.

One way to fix would be to change the return type to a reference (you'd have to make the same change where GetNodesCollection is defined)

std::vector<Node>& GetNodesCollection();
Community
  • 1
  • 1
Graham Griffiths
  • 2,196
  • 1
  • 12
  • 15