Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/140.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;:转换标准::映射<;标准::字符串,双精度>;至标准::映射<;标准::字符串_视图,双精度>;_C++_C++17 - Fatal编程技术网

C++ c++;:转换标准::映射<;标准::字符串,双精度>;至标准::映射<;标准::字符串_视图,双精度>;

C++ c++;:转换标准::映射<;标准::字符串,双精度>;至标准::映射<;标准::字符串_视图,双精度>;,c++,c++17,C++,C++17,假设我的类中有一个私有的std::map。如何将is转换为std::map以返回给用户?我希望这里有以下原型 const std::map<std::string_view, double>& MyClass::GetInternalMap() const; const std::map& MyClass::GetInternalMap()常量; 您不应按常量引用返回新的映射。当GetInternalMap()退出时,您将返回对临时map的悬空引用,该映射已被销毁。如果要返

假设我的类中有一个私有的
std::map
。如何将is转换为
std::map
以返回给用户?我希望这里有以下原型

const std::map<std::string_view, double>&
MyClass::GetInternalMap() const;
const std::map&
MyClass::GetInternalMap()常量;

您不应按常量引用返回新的
映射。当
GetInternalMap()
退出时,您将返回对临时
map
的悬空引用,该映射已被销毁。如果要返回常量引用,则应按原样返回源
map
,例如:

常量std::map&MyClass::GetInternalMap()常量 { 返回myvalue; }
否则,请按值返回新的
map

std::map MyClass::GetInternalMap()常量;
也就是说,
std::map
不能直接转换为
std::map
,因此您必须一次手动迭代源
map
一个元素,将每个元素分配给目标
map
,例如:

std::map MyClass::GetInternalMap()常量
{
映射结果;
对于(自动&p:myvalues){
结果[p.first]=p.second;
//或:结果。安放(第一页,第二页);
}
返回结果;
}
幸运的是,
std::pair
可以隐式转换为
std::pair
,因此您只需使用以迭代器范围为输入的
map
构造函数,并让
map
为您分配元素,例如:

std::map MyClass::GetInternalMap()常量
{
返回{myvalues.begin(),myvalues.end()};
}

动机是什么?返回一个
常量&
实际上已经是一个“视图”。不会复制任何底层内存。@0x5453目前我正在清理代码以优化性能,这对我来说是一个如何以更好的方式执行的问题。这个确切的例子只是我意图的一个说明。有一个很大的区别:string是拥有的,string_视图不是。所以他们不一样。非常感谢你的快速回答!我在这里寻找任何类型的stl解决方案,但是您的方法对我来说也很好,我认为您可以直接使用两个迭代器构造函数构造
结果
映射。我测试了GCC、Clang和MSVC;他们都接受
返回{begin(myvalues),end(myvalues)}作为整个函数体。