rainit2006 / Python-room

my python room
0 stars 0 forks source link

Python convert to C++/C# #18

Open rainit2006 opened 5 years ago

rainit2006 commented 5 years ago
rainit2006 commented 5 years ago

■ dict - > std::map

#python

d = {}

d[(0,0)] = 0
d[(1,2)] = 1
d[(2,1)] = 2
d[(2,3)] = 3
d[(3,2)] = 4

for (i,j) in d:
    print d[(i,j)], d[(j,i)]

C++

#include <iostream>
#include <map>

typedef std::map<std::pair<int, int>, int> Dict;
typedef Dict::const_iterator It;

int main()
{
   Dict d;

   d[std::make_pair(0, 0)] = 0;
   d[std::make_pair(1, 2)] = 1;
   d[std::make_pair(2, 1)] = 2;
   d[std::make_pair(2, 3)] = 3;
   d[std::make_pair(3, 2)] = 4;

   for (It it(d.begin()); it != d.end(); ++it)
   {
      int i(it->first.first);
      int j(it->first.second);
      std::cout <<it->second <<' '
                <<d[std::make_pair(j, i)] <<'\n';
   }
}

C# ex1 Dictionary<string, List> graph = new Dictionary<string, List>(); ex2 MyObject a = new MyObject(), b = new MyObject(), c = new MyObject(); Dictionary<string, MyObjectdict = new Dictionary<string, MyObject>(); dict["a"] = a; dict["b"] = b; dict["c"] = c;

■リスト型 python squares = [1, 4, 9, 16, 25] C++ std::vectors, std::lists, and arrays (or std::arrays) all have features similar to Python lists. https://stackoverflow.com/questions/17528657/python-list-equivalent-in-c C# var squares = new List<int>() { 1, 4, 9, 16, 25 };

要素追加

# python
list = ["A", "B", "C"]
list.append("D")
list.insert(1, "D") # ["A", "D", "B", "C"]
C#
var list2 = new List<T>();
list2.Add(T1); // 末尾に追加
list2.AddAddRange(anotherCollection); // 末尾に複数を追加

// 3. Insertメソッド/InsertRangeメソッドを使う方法
list2.Insert(0, T2); // 先頭に挿入
list2.Insert(list2.Count, T3); // 末尾に追加
list2.InsertRange(2, anotherCollection); // 3番目から複数を挿入
rainit2006 commented 5 years ago

for文 python

# python リストの作成
animals = ["cat", "dog", "mouse"]
for a in animals:
    print(a, len(a))

C#

var animals = new List<string>() { "cat", "dog", "mouse" };
foreach (var a in animals) {
    Console.WriteLine(string.Format("{0} {1}", a, a.Length));
}