C++ std::map::find to C# 字典<键,val>

c++ std::map::find to c# dictionary<key,val>

本文关键字:lt val gt 字典 map std find to C++      更新时间:2023-10-16

再次进行语言转换。

我有一个 c++ std::map,我需要转换为 C#。 我相信它相当于一本字典。

我真正需要理解的地方是在 c++ 代码中有 map::find - 我需要在 C# 中做类似的事情,但还没有完全理解它。

C++代码块

map<int, CAG_StatementWriter*> m_Writer;
map<int, DWORD> m_Counter;
other program code ....
int nPhysicalPages = 1 + nTextPages / 2;  //Statement.m_nTotalPages
map<int, CAG_StatementWriter*>::iterator iter = m_Writer.find(nPhysicalPages);
if (iter == m_Writer.end() ||
(nPhysicalPages == 1 && m_Counter[1] % 2000 == 0) ||
(nPhysicalPages == 2 && m_Counter[2] % 1000 == 0)
)
{
// working code here
}

C# 代码块

public static Dictionary<int, Writer> sWriter = new Dictionary<int, Writer>();
public static Dictionary<int, int> Counter { get; set; }
other program code... 
int physicalPages = 1 + textPages / 2;
Dictionary<int, Writer>.ValueCollection iter = sWriter.<>(physicalPages);
if (iter == sWriter.<> ||
   (physicalPages == 1 && Counter[1] % 2000 == 0) ||
   (physicalPages == 2 && Counter[2] % 1000 == 0))
{
    // working code here
}

我试图弄清楚什么会取代 c++ ::iterator。 我知道价值收集不正确;这就是我决定发布问题时所尝试的。

C# 没有像 C++ 这样的迭代器

查找字典中可能存在也可能不在字典中的值

Writer w = null;
if(sWriter.TryGetValue(physicalPage, out w))
{
   // found and w has the found Writer object
}

如果你知道它在那里(或者不介意扔,如果不是(

Writer w = sWriter[physicalPage];

Dictionary 等效的 find 是 TryGetValue。与返回迭代器的 find 不同,TryGetValue 返回一个布尔值,并采用一个 out 参数,如果该参数在集合中,则接收该值。