TinyXML Iterating over a Subtree - tinyxml

Does anyone have code to iterate through the nodes of a subtree in TinyXML? IE: Given a parent, iterate through all its children and all of its children's children?

Begemoth's answer sounds pretty good to me.
Here is a simplified version of TiXmlElement's Accept() method, that doesn't use a visitor and instead takes a TiXmlNode* as the parameter:
void TiXmlIterator::iterate(const TiXmlNode* el)
{
cout << "Iterating Node " << el->Value() << endl;
// More useful code here...
for (const TiXmlNode* node=el->FirstChild(); node; node=node->NextSibling())
{
iterate(node);
}
// And/Or here.
}
The Accept() method takes a TiXmlVisitor as a parameter and does all the iterating for you, though. And you don't have to call it on the whole document, just the root node of the subtree you want to traverse. This way, you can define specific behavior for the subclasses of TiXmlNode, by overriding the right methods. Look at the implementation of TiXmlPrinter in TinyXml's source code for a good example of how it's done.
In case you don't want to do that, here is another example:
bool MyTiXmlVisitor::Visit(const TiXmlText& text)
{
cout << "Visiting Text: " << text.Value() << endl;
return true; // This will ensure it keeps iterating
}
This will act on all text elements in the subtree of the node you call Accept() on. To act on all the elements, override the remaining virtual methods of TiXmlVisitor. Then, in the code where you want to iterate over the subtree, do the following:
subtree_root_node->Accept( my_tixmlvisitor_object );

You can use Visitor pattern implementation in the library. Create a class inherited from TiXmlVistor, override necessary methods like VisitElement, then call Accept() method for a particular node.

Related

Recursive Print Function for Linked List

So my professor would like us to design recursive functions for a linked list from this class 'addressBookType' which is derived from 4 other classes. The program basically creates an address book with the person's name, address, date, and relationship, each of those has their own classes.
The recursive functions she wants to make are a print, append, delete, and sequential search.
But here's the problem. The main premise around a function being recursive is that it's supposed to call itself in the function definition right? I successfully made the recursive append function, but I'm having trouble with the recursive print function.
Here is what the original print function and the recursive print function are:
void addressBookType::displayList() const
{
ListNode *nodePtr; // To move through list
nodePtr = head; // start at the head of list
while(nodePtr != NULL) // while nodePtr points to a node, move through list
{
displayListRecursive(nodePtr);
nodePtr = nodePtr->next;
}
}
void addressBookType::displayListRecursive(ListNode *node) const
{
if(node != NULL)
{
(node->value).print();
displayListRecursive(node->next);
}
}
The trouble I'm having is that when I run the program, everything prints and then it starts printing at the second object until there is one object left. Here's what I mean when it prints:
1
2
3
4
2
3
4
3
4
4
I would paste what the actual output is but it is VERY lengthy, as each object displays the person's first name, last name, address, street, zipcode, city, state, date, and relationship type.
Whenever I take out the displayListRecursive(node->next) in the displayListRecursive function, everything prints fine. But then it's not really a recursive function right? Or is it? Anyone have some answers that can explain this? (I'm REALLY new to recursive)
I think the recursive definition is fine. It will print the node you provide and then call itself with the next one until its NULL.
So you just need to call the recursive function from the first node.
The problem is that you are calling it multiple times with all the nodes in the while loop of displayList.
I think that if you just remove the while loop it should work as you expect.
Something like this:
void addressBookType::displayList() const
{
displayListRecursive(head);
}
void addressBookType::displayListRecursive(ListNode *node) const
{
if(node != NULL)
{
(node->value).print();
displayListRecursive(node->next);
}
}

Find element that goes before target with C++ set

I know there's lower_bound and upper_bound method which both find first element that doesn't go before target element, include and exclude the target. But I need a method that can find the last element that goes before target. Is there such method or easy way to do this using set?
Thanks!
You could just decrement the lower bound?
In general you need to check if the lower bound yields the begin() iterator, in which case the element you mention doesn't exist.
Here's some example code (untested, just to give the idea):
template<typename T>
std::set<T>::iterator get_last_before(std::set<T> & s, const T & t) {
auto it = s.lower_bound(t);
if (it == s.begin()) { throw std::runtime_error(); }
return --it;
}

Equivalent of enumerators in C++11?

In C#, you can define a custom enumeration very trivially, eg:
public IEnumerable<Foo> GetNestedFoos()
{
foreach (var child in _SomeCollection)
{
foreach (var foo in child.FooCollection)
{
yield return foo;
}
foreach (var bar in child.BarCollection)
{
foreach (var foo in bar.MoreFoos)
{
yield return foo;
}
}
}
foreach (var baz in _SomeOtherCollection)
{
foreach (var foo in baz.GetNestedFoos())
{
yield return foo;
}
}
}
(This can be simplified using LINQ and better encapsulation but that's not the point of the question.)
In C++11, you can do similar enumerations but AFAIK it requires a visitor pattern instead:
template<typename Action>
void VisitAllFoos(const Action& action)
{
for (auto& child : m_SomeCollection)
{
for (auto& foo : child.FooCollection)
{
action(foo);
}
for (auto& bar : child.BarCollection)
{
for (auto& foo : bar.MoreFoos)
{
action(foo);
}
}
}
for (auto& baz : m_SomeOtherCollection)
{
baz.VisitAllFoos(action);
}
}
Is there a way to do something more like the first, where the function returns a range that can be iterated externally rather than calling a visitor internally?
(And I don't mean by constructing a std::vector<Foo> and returning it -- it should be an in-place enumeration.)
I am aware of the Boost.Range library, which I suspect would be involved in the solution, but I'm not particularly familiar with it.
I'm also aware that it's possible to define custom iterators to do this sort of thing (which I also suspect might be involved in the answer) but I'm looking for something that's easy to write, ideally no more complicated than the examples shown here, and composable (like with _SomeOtherCollection).
I would prefer something that does not require the caller to use lambdas or other functors (since that just makes it a visitor again), although I don't mind using lambdas internally if needed (but would still prefer to avoid them there too).
If I'm understanding your question correctly, you want to perform some action over all elements of a collection.
C++ has an extensive set of iterator operations, defined in the iterator header. Most collection structures, including the std::vector that you reference, have .begin and .end methods which take no arguments and return iterators to the beginning and the end of the structure. These iterators have some operations that can be performed on them manually, but their primary use comes in the form of the algorithm header, which defines several very useful iteration functions.
In your specific case, I believe you want the for_each function, which takes a range (as a beginning to end iterator) and a function to apply. So if you had a function (or function object) called action and you wanted to apply it to a vector called data, the following code would be correct (assuming all necessary headers are included appropriately):
std::for_each(data.begin(), data.end(), action);
Note that for_each is just one of many functions provided by the algorithm header. It also provides functions to search a collection, copy a set of data, sort a list, find a minimum/maximum, and much more, all generalized to work over any structure that has an iterator. And if even these aren't enough, you can write your own by reading up on the operations supported on iterators. Simply define a template function that takes iterators of varying types and document what kind of iterator you want.
template <typename BidirectionalIterator>
void function(BidirectionalIterator begin, BidirectionalIterator end) {
// Do something
}
One final note is that all of the operations mentioned so far also operate correctly on arrays, provided you know the size. Instead of writing .begin and .end, you write + 0 and + n, where n is the size of the array. The trivial zero addition is often necessary in order to decay the type of the array into a pointer to make it a valid iterator, but array pointers are indeed random access iterators just like any other container iterator.
What you can do is writing your own adapter function and call it with different ranges of elements of the same type.
This is a non tested solution, that will probably needs some tweaking to make it compile,but it will give you an idea. It uses variadic templates to move from a collection to the next one.
template<typename Iterator, Args...>
visitAllFoos(std::pair<Iterator, Iterator> collection, Args&&... args)
{
std::for_each(collection.first, collection.second, {}(){ // apply action });
return visitAllFoos(std::forward<Args>(args)...);
}
//you can call it with a sequence of begin/end iterators
visitAllFoos(std::make_pair(c1.begin(), c1,end()), std::make_pair(c2.begin(), c2,end()))
I believe, what you're trying to do can be done with Boost.Range, in particular with join and any_range (the latter would be needed if you want to hide the types of the containers and remove joined_range from the interface).
However, the resulting solution would not be very practical both in complexity and performance - mostly because of the nested joined_ranges and type erasure overhead incurred by any_range. Personally, I would just construct std::vector<Foo*> or use visitation.
You can do this with the help of boost::asio::coroutine; see examples at https://pubby8.wordpress.com/2014/03/16/multi-step-iterators-using-coroutines/ and http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/overview/core/coroutine.html.

Understanding pre/post in pseudo-code notation

I am following these examples of C# code. But I am little confused by the Pseudo Code comments all over the place.
For example:
public void addToHead(Object value)
// pre: value non-null
// post: adds element to head of list
{
SinglyLinkedListElement temp =
new SinglyLinkedListElement(value);
if (tail == null) {
tail = temp;
tail.setNext(tail);
}
else {
temp.setNext(tail.next());
tail.setNext(temp);
}
count++;
}
What does Pre and Post mean here?
I've never seen Post used here. I know what Post means in the context of the Web and HTML etc, but not in pure code.
"Pre" indicates an assumption made at the beginning of execution. In this case, it's indicating that the value passed in is assumed to be not null.
"Post" indicates an assumption made at the end of the execution, i.e. what the routine actually does. In this case, when the routine finishes a new element will have been added to the end of the list. If the routine modifies its parameters or has any other side effects, those modifications should be listed in the "Post" as well.

Print a simply linked list backwards with no recursion, in two passes at most, using constant extra memory, leaving it intact

You must print a simply linked list backwards:
Without recursion
With constant extra memory
In linear time
Leaving the list intact
Added Later Two passes at most
Invert the list, print it forwards, invert again. Each step can be done without violating restrictions except the last one.
EDIT: As cube notes in the comments the second and the third stages can be combined into one pass. This gives two passes – first reverse, then print while reversing again.
Building on sharptooth's reply, you can combine the printing and second inversion in the same pass.
Edit: The "list is left intact" from a single-threaded view because the post-condition equals the pre-condition.
Edit 2: Not sure how I got the answer, but I'll take it since I've hit the rep cap for the day. I gave sharptooth a +1 too.
Here's a C# implementation that holds for all the current rules. It mutates the list during the execution, but the list is restored before returning.
using System;
using System.Diagnostics;
namespace SO1135917.Classes
{
public class ReverseListPrinter
{
public static void Execute(Node firstNode, Action<Node> action)
{
Reverse(Reverse(firstNode, null), action);
}
private static Node Reverse(Node firstNode, Action<Node> action)
{
Node node = firstNode;
Debug.Assert(node != null);
Node nextNode = node.Next;
node.Next = null;
while (node != null)
{
if (action != null)
action(node);
if (nextNode == null)
break;
Node nextNode2 = nextNode.Next;
nextNode.Next = node;
node = nextNode;
nextNode = nextNode2;
}
return node;
}
}
}
There is one problem, however, and that is that the state of the list is undefined if an exception should occur in the above methods. Probably not impossible to handle though.
A subversion repository of the above code, with unit tests, for Visual Studio 2008 is available here, username and password is both 'guest' without the quotes.
You can first check the length of the list. Then create a print-buffer, which you fill in backwards as you traverse the list once again for the information.
Or
You can create another linked list where you add all the printing data in the front when you traverse the first list, and then print the second list from front to back.
Either way makes only two passes at most. The first idea could be done in one pass if you have a header struct that keeps track of the amount of elements in the list.
Edit: I just realised that these ideas does not use constant memory.
The only way to do this sensibly seems to be Sharptooths reply, but that requires three passes.
a function like the following might solver your issue:
void invert_print(PtNo l){
PtNo ptaux = l;
PtNo last;
PtNo before;
while(ptaux != NULL){
last = ptaux;
ptaux = ptaux->next;
}
while(ptaux != last){
printf("%s\n", last->info.title);
ptaux = l;
before = last;
while(ptaux != before){
last = ptaux;
ptaux = ptaux->next;
}
}
}
you will need a structure like the following:
typedef struct InfoNo{
char title20];
}InfoNo;
typedef struct aPtNo{
struct InfoNo info;
struct aPtNo* nextx;
}*PtNo;
Objective-C Link class with reverse method:
Link.h
#import <Foundation/Foundation.h>
#interface Link : NSObject
#property(nonatomic) int value;
#property(nonatomic) Link *next;
- (Link*)reversedList;
#end
Link.m
#import "Link.h"
#implementation Link
- (Link*)reversedList {
Link* head;
Link *link = self;
while (link) {
// save reference to next link
Link *next = link.next;
// "insert" link at the head of the list
link.next = head;
head = link;
// continue processing the rest of the list
link = next;
}
return head;
}
#end

Resources