migration C#, Java, C++ (day 3)

logo

Containers in C++ are like C# collections.
The sequential containers are vector, deque and list. The latter is by far the slowest one. List comes close to LinkedList in C#. Vector and deque are like Lists in C#.

Available Methods:

vector deque list
similar in C# List List LinkedList
front(), back() yes yes yes
push_back(), pop_back() yes yes yes
push_front(), pop_front() no yes yes
at(), operator [] yes yes no
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
#include <vector>
#include <deque>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <memory>

LinkedList

LinkedList<string> lLinkedList = new LinkedList<string>();
LinkedListNode<string> lLast = lLinkedList.AddLast("Last");
LinkedListNode<string> lFirst = lLinkedList.AddFirst("First");
LinkedListNode<string> lMid = lLinkedList.AddAfter(lFirst, "Mid");
bool b1 = lLinkedList.Contains("Last");
LinkedListNode<string> lFind = lLinkedList.Find("Last");
lLinkedList.Remove("First");
lLinkedList.RemoveFirst();
lLinkedList.Remove(lLast);
lLinkedList.Clear();
java.util.LinkedList<String> lLinkedList = new java.util.LinkedList<String>();
lLinkedList.addLast("Last");
lLinkedList.addFirst("First");
lLinkedList.add(1, "Mid");
boolean b1 = lLinkedList.contains("Last");
int lFind = lLinkedList.indexOf("Last");
//lLinkedList.remove(lFind);
lLinkedList.remove("First");
lLinkedList.removeFirst();
lLinkedList.removeLast();
lLinkedList.clear();
list<string> lLinkedList = list<string>();
lLinkedList.push_back("Last");
lLinkedList.push_front("First");
list<string>::iterator lIterator = lLinkedList.begin();
lIterator++;
lLinkedList.insert(lIterator, "Mid1");
lLinkedList.insert(lIterator, "Mid2");
cout << "List: " << endl;
for (lIterator = lLinkedList.begin(); lIterator != lLinkedList.end(); lIterator++)
	cout << *lIterator << " ";	//List:	First Mid1 Mid2 Last

lLinkedList.remove("First");
lLinkedList.pop_front();
lLinkedList.remove("Mid2");
cout << endl << endl << "List: " << endl;
for (lIterator = lLinkedList.begin(); lIterator != lLinkedList.end(); lIterator++)
	cout << *lIterator << " ";	//List: Last

lLinkedList.clear();

List

List<string> lList = new List<string>();
lList.Add("First");
lList.AddRange(new string[] { "Mid1", "Last" });
bool b2 = lList.Contains("Mid1");
lList.Insert(2, "Mid2"); // First, Mid1, Mid2, Last
lList.Reverse(); // Last, Mid2, Mid1, First
lList.Sort(); // First, Last, Mid1, Mid2
string[] lStringArray = lList.ToArray();
lList.Clear();
java.util.ArrayList<String> lList = new java.util.ArrayList<String>();
lList.add("First");
lList.addAll(Arrays.asList("Mid1", "Last"));
boolean b2 = lList.contains("Mid1"); // true
lList.add(2, "Mid2"); // First, Mid1, Mid2, Last
java.util.Collections.reverse(lList); // Last, Mid2, Mid1, First
java.util.Collections.sort(lList); // First, Last, Mid1, Mid2
String[] lStringArray = lList.toArray(new String[0]);
lList.clear();
inline bool MyDataSortPredicate(const string &s1, const string &s2) { return s1 < s2; }

vector<string> lList = vector<string>();
lList.push_back("First");
string lArray[] {lList.front(), "Mid", "Last"};
lList.assign(lArray, lArray + 3);
lList.push_back("VeryLast"); // First, Mid, Last, VeryLast
reverse(lList.begin(), lList.end()); // VeryLast, Last, Mid, First
sort(lList.begin(), lList.end(), MyDataSortPredicate); // First, Last, Mid, VeryLast
string *lStringArray = lList.data();
lStringArray++;
string lResult = lStringArray[1]; // Mid
lList.clear();

deque<string> lList2 = deque<string>();
lList2.push_back("First");
string lArray2[] {lList2.front(), "Mid", "Last"};
lList2.assign(lArray2, lArray2 + 3);	
auto lIterator2 = lList2.end();
lIterator2--;
lList2.emplace(lIterator2, "Mid2");
lList2.push_back("VeryLast"); // First, Mid, Mid2, Last, VeryLast
reverse(lList2.begin(), lList2.end()); // VeryLast, Last, Mid2, Mid, First
sort(lList2.begin(), lList2.end(), MyDataSortPredicate); // First, Last, Mid, Mid2, VeryLast	
lList2.clear();

Collections comparison

// key value pairs (no duplicate keys)
Dictionary<string, string> lDictionary = new Dictionary<string, string>(); // uses a hashmap
SortedDictionary<string, string> lSortedDictionary = new SortedDictionary<string, string>(); // uses a binary tree
SortedList<string, string> lSortedList = new SortedList<string, string>(); // uses arrays

// lists
List<string> lList3 = new List<string>(); // duplicate entries allowed
HashSet<string> lHashSet = new HashSet<string>(); // a List with no duplicates entries; behaves like a Dictionary with key==value
SortedSet<string> lSortedSet = new SortedSet<string>(); // a sorted list with no duplicates; behaves like a SortedDictionary with key==value
// key value pairs (no duplicate keys)
java.util.HashMap<String, String> lDictionary = new java.util.HashMap<String, String>();
java.util.TreeMap<String, String> lSortedDictionary = new java.util.TreeMap<String, String>();
// There is no such as a SortedList in Java

// lists
java.util.ArrayList<String> lList3 = new java.util.ArrayList<String>();
java.util.HashSet<String> lHashSet = new java.util.HashSet<String>();
java.util.TreeSet<String> lSortedSet = new java.util.TreeSet<String>();
// key value pairs (no duplicate keys)
unordered_map<string, string> lDictionary = unordered_map<string, string>(); // uses a hashmap
map<string, string> lSortedDictionary = map<string, string>(); // uses a binary tree
// lSortedList = no equivalent 

// lists
vector<string> lList2 = vector<string>(); // duplicate entries allowed
unordered_set<string> lHashSet = unordered_set<string>(); // a List with no duplicates entries; behaves like a Dictionary with key==value
set<string> lSortedSet = set<string>(); // a sorted list with no duplicates; behaves like a SortedDictionary with key==value

Threading

void f1() {
   Thread.Sleep(500);
   Console.WriteLine("f1 says: Hello world!");
}

void f2(object o) {
   Thread.Sleep(1000);
   string s;
   if (o is string) s = o as string;
   else {
      // for sure using a "volatile" variable in a class as storage would be a better approach
      string[] h = (string[])o;
      s = h[0];
      h[0] = "new Message";
   }
   Console.WriteLine("f2 says: " + s);
}


Console.WriteLine("The parent thread id is: " + Thread.CurrentThread.ManagedThreadId);

Thread t1 = new Thread(f1); // "f1 says: Hello world!"
t1.IsBackground = true; // not the same as daemon! It is a background thread that is dependent from the main thread.
t1.Start();
t1.Join();

string lByVal = "Agent Smith is everywhere :(";
Thread t2 = new Thread(f2); // "f2 says: Agent Smith is everywhere :("
t2.Start(lByVal);

string[] lByRef = { "Agent Smith is everywhere :(" };
Thread t3 = new Thread(f2); // "f2 says: Agent Smith is everywhere :("
t3.Start(lByRef);
t3.Join();
Console.WriteLine("same text? " + lByRef[0]); // "same text? new Message"         
class Class1 implements Runnable {
  @Override
  public void run() {
    try { Thread.sleep(500); }
    catch (InterruptedException e) { e.printStackTrace(); }
    System.out.println("c1 says: Hello world!");      
    }
 } // class

class Class2 implements Runnable {
  private Object _Parameter;

  public Class2(Object xParameter) {
    _Parameter = xParameter;
  } // constructor
  
  public void run() {
    try { Thread.sleep(1000); }
    catch (InterruptedException e) { e.printStackTrace(); }
    String s;
    if (_Parameter instanceof String) s = (String)_Parameter;
    else {
       String[] h = (String[])_Parameter;
       s = h[0];
       h[0] = "new Message";
    }
    System.out.println("c2 says: " + s);   
  } //
} // class

System.out.println("The parent thread id is: " + Thread.currentThread().getId());

Class1 lInstance1 = new Class1();
Thread t1 = new Thread(lInstance1); // "c1 says: Hello world!"
t1.setDaemon(true); 
t1.start();
try { t1.join(); }
catch (InterruptedException e) { e.printStackTrace(); }

String lByVal = "Agent Smith is everywhere :(";
Class2 lInstance2 = new Class2(lByVal);   
Thread t2 = new Thread(lInstance2); // "c2 says: Agent Smith is everywhere :("
t2.start();

String[] lByRef = {"Agent Smith is everywhere :("};
Class2 lInstance3 = new Class2(lByRef);
Thread t3 = new Thread(lInstance3); // "c2 says: Agent Smith is everywhere :("
t3.start();
try { t3.join(); }
catch (InterruptedException e) { e.printStackTrace(); }
System.out.println("same text? " + lByRef[0]); // "same text? new Message"
void f1() {
	this_thread::sleep_for(chrono::milliseconds(500));
	cout << "f1 says: Hello world!" << endl;
}

void f2(string xMessage) {
	this_thread::sleep_for(chrono::milliseconds(1000));
	cout << "f2 says: " << xMessage << endl;
}

class f3 {
public:
	void operator()(string &xMessage) { 
		this_thread::sleep_for(chrono::milliseconds(1500));
		cout << "functor f3 says: " << xMessage << endl; 
		xMessage = "new Message";
	}
};

cout << "The parent thread id is: " << this_thread::get_id() << endl;

thread t1(f1); // "f1 says: Hello world!"
t1.detach(); // t1 becomes a daemon process (background + no terminal)
if (t1.joinable()) t1.join(); // joinable() returns false

thread t2(f2, "Mr Anderson is Neo."); // "f2 says: Mr Anderson is Neo."
string lByValue = "Agent Smith is everywhere :(";
thread t3((f3()), lByValue); // functor f3 says: Agent Smith is everywhere :("

t2.join();
t3.join();

cout << "same text? " << lByValue << endl;  // "same text? Agent Smith is everywhere :("
	
string lByRef = lByValue;
thread t4((f3()), ref(lByRef));  // "functor f3 says: Agent Smith is everywhere :("
	
// so that the call by reference can assign a new value
// play with this value
t4.join(); 

cout << "same text? " << lByRef << endl;  // "same text? new Message"

About Bastian M.K. Ohta

Happiness only real when shared.

Posted on February 26, 2014, in C#, C++, Java and tagged , , , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: