Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Compile and Execute D Online

import std.stdio;
import std.typecons;

struct Semimap (K,V) {
    private Nullable!(V)[K] stuff;
    
    void set(int key) {
        stuff[key] = Nullable!V();
    }
    
    void set(int key, string value) {
        stuff[key] = value;
    }
    
    auto values() {
        V[] stuffValues;
        foreach(v;stuff.values)
            if(!v.isNull)
                stuffValues ~= v;
        
        return stuffValues;
    }
    
    auto byValue() {
        return stuff.values;
    }
    
    auto keys() {
        return stuff.keys;
    }
    
    auto byKey() {
        return stuff.keys;
    }
    
    auto get(int key){
        return stuff[key];
    }
    
    
    bool hasKey(int key){
        foreach(k;stuff.keys()){
            if(k == key){
                return true;
            }
        }
        return false;
    }
    
    int singCount() {
        int singleCount;
        foreach(v;stuff.values)
            if(v.isNull)
                singleCount++;
        
        return singleCount;
    }
    
    int pairCount() {
        int pairCount;
        foreach(v;stuff.values)
            if(!v.isNull)
                pairCount++;
        
        return pairCount;
    }
}

void main() {
    Semimap!(int,string) sm;
    sm.set(1,"one");
    sm.set(2);
    sm.set(3);
    writeln(sm.singCount);
    writeln(sm.pairCount);
    writeln(sm.values);
    writeln(sm.keys);
    auto val = sm.get(2);
    assert(val.isNull);
    writeln(sm.hasKey(2));
    writeln(sm.hasKey(3));
    foreach(k; sm.byKey)
        writeln("key = ",k);
    foreach(v; sm.byValue)
        if (!v.isNull)
            writeln("value = ",v);
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.