Search code examples
c++classfriend

How to find all mutual friendships in large C++ source tree?


In a large C++ source tree, with about 600 or so classes defined, I want to find all pairs of classes where each declares the other a friend.

There are many cases of one class being a friend of another, too many to make it worth wading through a simple grep result.


Solution

  • You could implement a kind of triple loop here; the algorithm could be as follows:

    1. First loop: find all classes who have friends, and remember the name of the friend and the name of the actual class;
    2. Then run inner loop for all the classes and find a class with the name of the friend from step 1.
    3. Then run another inner loop through all the friends of the class found at step 2. If you have found class with name from step 1 - voila - they're mutual friends.

    I believe Perl and regexes are the best tools for such things.

    P.S. sure this approach has its limits, because not everything in C++ could be parsed with regex (using namespace stuff is the first thing came into my mind). But, to some extent, this is working approach, and if you don't have alternatives, you could give it a try.

    EDIT: An idea came to my mind today in the morning, while I still was lying in my bed. :) The idea is quite simple and clear (like all morning ideas): use SQL! Naturally, imagine you have a table of classes with 2 columns, where first column is class name, and second column is it's friend`s name. Say, something like this:

    ClassName FriendName
    C1        C2
    C1        C3
    C1        C4
    C2        C1
    C2        C8
    C3        C1
    C3        C2
    ...       ...
    

    Then you can run a simple query against it. Say, something like this (sorry, I don't have any SQL DB handy, so have not checked the query, but I hope you'll got the idea and implement it as needed:

    SELECT ClassName as c, FriendName as f FROM T
    WHERE c in 
      (SELECT FriendName FROM T
         WHERE FriendName = c AND ClassName = f)
    

    The idea behind this variant is that we should employ those tolls which exactly fit the task. What can compare to SQL when you need to crunch some sets of data?