Lab 6: Semantic Analysis Part 1 - Symbol Tables

  1. for_each()
    #include <stdio.h>
    #include <list>
    #include <algorithm>
    
    using namespace std;
    
    class A {
    private:
        int i;
    
    public:
        A(int i) : i(i) {
        }
        void display(void) const {
    	printf("%d\n", i);
        }
    };
    
    void apply(A *a) {
        a->display();
    }
    
    int main(void) {
        list<A *> l;
        l.push_back(new A(1));
        l.push_back(new A(2));
        l.push_back(new A(3));
        l.push_back(new A(4));
    
        // One way to iterate all elements of a list is to use iterator
        for (list<A *>::iterator itr = l.begin(); itr != l.end(); itr++) {
    	(*itr)->display();
        }
    
        // Another way is to use for_each() with a function
        for_each(l.begin(), l.end(), apply);
    
        return (0);
    }
    
  2. map
    #include <stdio.h>
    #include <string>
    #include <map>
    #include <algorithm>
    #include <iostream>
    
    using namespace std;
    
    typedef map<string, int> scores_t;
    
    int main(void) {
        scores_t scores;
        
        // Assign scores
        scores["Lee"] = 100;
        scores["Tom"] = 90;
        scores["Ada"] = 95;
        scores["Bob"] = 60;
    
        for (scores_t::iterator itr = scores.begin();
    	 itr != scores.end();
    	 itr++) {
    	printf("%s - %d\n", itr->first.c_str(), itr->second);
    	//cout << itr->first << " - " << itr->second << endl;
        }
    
        // Look up using find()
        scores_t::iterator found = scores.find("Lee");
        if (found == scores.end()) {
    	fprintf(stderr, "Can't find Lee\n");
        } else {
    	printf("Lee has score of %d\n", found->second);
        }
    
        return (0);
    }
    
  3. template
    #include <stdio.h>
    
    // Function template
    template <class T>
    T max(T a, T b) {
        return (a > b) ? a : b;
    }
    
    int main(void) {
        printf("max(2,6) = %d\n", max(2,6));
        printf("max(2.0,6.0) = %.1f\n", max(2.0,6.0));
        printf("max('b','a') = %c\n", max('b','a'));
        return (0);
    }