【问题标题】:C++: map<wstring,wstring> Getting second from firstC++:map<wstring,wstring> 从第一个获得第二个
【发布时间】:2013-05-22 12:25:37
【问题描述】:

我有一个

map <wstring,wstring>.

我已经插入了这样的对:

m_Translations.Content().insert(pair<wstring,wstring>(L"rome",L"roma"));
m_Translations.Content().insert(pair<wstring,wstring>(L"water",L"aqua"));

如何从地图中确定“水”的翻译? 换句话说:我想从第一个项目中获得第二个项目。 搜索区分大小写。

感谢您的帮助!

【问题讨论】:

  • wstring s = m_Translations.Content()[L"water"];
  • @AlexFarber:如果缺少空条目,您可能不想插入它。
  • @Mike Seymour - 这是作为评论发布的提示与完整答案之间的区别。

标签: c++ map wstring


【解决方案1】:

有点奇怪的问题。使用operator[] 访问地图的默认方式呢?

wstring aqua = m_Translations.Content()[L"water"];

如果您不确定是否存在翻译,可以使用find 方法检查:

const auto& dict = m_Translations.Content();
auto pAqua = dict.find(L"water");

if (pAqua != dict.end())
{
  // Found it!
}
else
{
  // Not there...
}

【讨论】:

  • 谢谢。这是什么“汽车”?
  • 这是 C++11 风格。这意味着变量类型是从初始化表达式中自动推导出来的。您可以使用显式类型声明重写它。
  • 为什么不使用方法at?如果不存在具有指定键的元素,则会引发异常。
  • @Mikhail 我有一个问题,只是出于好奇。是否也可以使搜索不区分大小写?
  • @soon 也是正确的做法。我认为这是一个选择问题。但是,如果多次处理此请求,异常处理可能会出现一些性能问题。
【解决方案2】:

您可以使用std::map 上的operator[]

例如:

map<wstring, wstring> myMap = m_Translations.Content();

myMap.insert(pair<wstring, wstring>(L"rome", L"roma"));
myMap.insert(pair<wstring, wstring>(L"water", L"aqua"));

// waterText value would be 'aqua'
wstring waterText = myMap[L"water"];

【讨论】:

    猜你喜欢
    • 2013-12-13
    • 2016-03-16
    • 1970-01-01
    • 2011-06-17
    • 2019-10-19
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多