xml::document doc("blablabla.xml");xml::node root = doc.child("root");xml::node example = root.child("example");
C++ (Qt)QVector<int> vec = {1, 2, 3};const int &a = vec.at(3);vec << 4;
class Document;struct Item{ Document *document; Item *parent; std::vector<Item *> children;};class Document{ Item *rootItem;};
C++ (Qt)#include <iostream>#include "tree.h" using namespace std; int main(){ cout << "Start..." << endl; Document doc( "Test doc" ); ItemRef r = doc.root(); ItemRef c1 = r.new_child( "Child 1" ); ItemRef c2 = c1.new_child( "Child 2" ); cout << "Child2 is_valid: " << c2.is_valid() << " docname: " << c2.doc_name() << endl; r.remove_child( c1 ); cout << "Child2 is_valid: " << c2.is_valid() << " docname: " << c2.doc_name() << endl; return 0;}
C++ (Qt)#ifndef TREE_H#define TREE_H #include <string>#include <memory> using std::string;using std::shared_ptr;using std::weak_ptr;using std::make_shared; class Item; class ItemRef{public: bool is_valid() const; string name() const; void set_name( const string &val ); string doc_name() const; ItemRef new_child( const string &name ); void remove_child( const ItemRef &item ); private: ItemRef() {} ItemRef( const shared_ptr<Item> &item ) : m_ptr( item ) {} private: weak_ptr<Item> m_ptr; friend class Document;}; class Document{public: Document( const string &name = string() ); ItemRef root() const { return ItemRef( m_root ); } string name() const { return m_name; } private: shared_ptr<Item> m_root; string m_name;}; #endif // TREE_H
C++ (Qt)#include "tree.h"#include <deque>#include <algorithm> struct Item{ explicit Item( Document &document ) : m_document( document ) {} explicit Item( const shared_ptr<Item> &parent, const string &name = string() ) : m_document( parent->m_document ), m_parent( parent ), m_name( name ) {} explicit Item( Document &document, const string &name ) : m_document( document ), m_name( name ) {} void remove_child( const shared_ptr<Item> &item ) { m_children.erase( std::remove_if( m_children.begin(), m_children.end(), [item]( const shared_ptr<Item> &c ) { return c == item; } ), m_children.end() ); } Document &m_document; weak_ptr<Item> m_parent; std::deque<shared_ptr<Item>> m_children; string m_name;}; bool ItemRef::is_valid() const{ return m_ptr.lock() != nullptr;} string ItemRef::name() const{ auto p = m_ptr.lock(); return p? p->m_name : string();} void ItemRef::set_name( const string &val ){ auto p = m_ptr.lock(); if( p ) p->m_name = val;} string ItemRef::doc_name() const{ auto p = m_ptr.lock(); return p? p->m_document.name() : string();} ItemRef ItemRef::new_child( const string &name ){ auto p = m_ptr.lock(); if( p ) { shared_ptr<Item> item = make_shared<Item>( p, name ); p->m_children.push_back( item ); return ItemRef( item ); } return ItemRef();} void ItemRef::remove_child( const ItemRef &item ){ auto p = m_ptr.lock(); if( p ) p->remove_child( item.m_ptr.lock() );} Document::Document( const string &name ) : m_root( make_shared<Item>( *this ) ), m_name( name ){}