简体   繁体   中英

Postorder traversal in stl map

I am using a stl map on gcc comper which uses a tree to store key,value pairs. The iterator advances in an inorder fashion so inorder traversal is really easy. However one of my output requirements is a postorder traversal. I have been specifically aksed to use map. Is there any way to get it done?

There is no standard way to access the "actual tree structure" of an instance of std::map .

Furthermore, the standard doesn't know (or care) exactly how the elements of a map are arranged in any internal tree that the map might use. Red-Black trees and AVL trees are both valid implementations of std::map , and you'd get a different postorder traversal according to which is in fact used. In practice I expect its always RB or very similar, but the implementation freedom informs the interface defined by the standard.

In short, std::map is not a tree, it's an abstract data structure that can be (and is) implemented using a tree.

It might be possible to hack a particular implementation, but probably best not to. If you want the tree structure of your data to be part of the defined state of your program, you could perhaps write your own tree.

As Steve Jessop said Map is the abstract data structure provided by c++, you can not change the order of elements stored in map in any order, like we can do in Tree or AVL by traversing in pre/post/in order. but you can reverse the order of storing by using std::greater as your key instead of std::less .

eg

std::map< std::string, int, std::greater<std::string> > my_map; 

OR crate one Vector desiredOrder, which will keep the trac of order of insertion in map, and once you are done with insertion just do whatever sorting operation you want pre/post/ in order on the desiredOrder Vector and using for loop you can traverse the vector and access the Map elements using the vector value as a key for your Map

eg

std::vector<std::string> desiredOrder;
std::map<std::string, int> myTree;

myTree["A"] = 0;
desiredOrder.push_back("A"); 
myTree["B"] = 0;
desiredOrder.push_back("B");
myTree["C"] = 0;
desiredOrder.push_back("C");
myTree["D"] = 0;
desiredOrder.push_back("D");

/*
Do whatever sorting you want to do here....
*/

for (int i = 0; i < desiredOrder.size(); ++i)
{
    const std::string &s = desiredOrder[i];
    std::cout << s << ' ' << myTree[s] << '\n';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM