Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to translate make_pair in c++ to c#?

Tags:

c++

c#

map <pair<unsigned int, unsigned int>, unsigned int> kmapValues;

with

private Dictionary<KeyValuePair<uint, uint>, uint> kmapValues;

replace

kmapValues[make_pair(j, i)] = 1 

with

kmapValues[Tuple(j, i)] = 1 // got error

System.Tuple is type but used like a variable error

like image 378
Martin Avatar asked Apr 29 '13 10:04

Martin


People also ask

What does Make_pair return?

In line 6 a pair object is initialized, whose first value is of type int and the second value of type string . In line 7 the make_pair() function is invoked with the required values as its parameters. The function returns the newly created pair object. In lines 10 and 11 the individual pair object values are printed.

What is Std:: make_ pair?

std::make_pairCreates a std::pair object, deducing the target type from the types of arguments.

Is Make_pair necessary?

In C++11, you can almost entirely do without make_pair. See my answer. In C++17, std::make_pair is redundant.


2 Answers

You are declaring a dictionary to use KeyValuePair<K,V> keys, but you are trying to access it with Tuple<T1,T2> instead. You need to decide on one type, and stay with it.

Since KeyValuePair<K,V> is asymmetric, I would use Tuple<T1,T2>:

private Dictionary<Tuple<uint, uint>, uint> kmapValues;

Then your assignment would work correctly:

kmapValues[Tuple.Create(j, i)] = 1;
like image 129
Sergey Kalinichenko Avatar answered Sep 24 '22 18:09

Sergey Kalinichenko


// As a C# extension method, on some static class:

public static KeyValuePair<K, V> MakePair<K, V>(this K k, V v) { return new KeyValuePair<K, V>(k, v); }
like image 33
Kafka Avatar answered Sep 25 '22 18:09

Kafka