【问题标题】:Const map and its sizeconst 映射及其大小
【发布时间】:2020-06-08 12:40:14
【问题描述】:

我有一个std::map,它在运行时无法更改。因此,我已将其标记为 const 我无法将其标记为 constexpr,因为它是非文字类型。

我可以在编译时推导出这张地图的size吗?

#include <map>
#include<string>

int main (){
    const std::map <int, std::string> my_map { 
      { 42, "foo" }, 
      { 3, "bar" } 
    };

    constexpr auto items = my_map.size();
    return items;
}

This 无法编译并出现错误:

:10:20: 错误:必须初始化 constexpr 变量“项目” 通过常量表达式

constexpr auto items = my_map.size();

               ^       ~~~~~~~~~~~~~

:10:35: 注意:非 constexpr 函数 'size' 不能用于 一个常量表达式

constexpr auto items = my_map.size();

【问题讨论】:

  • 您使用的是哪个版本的 Cpp?这可能在这里相关
  • 不行,constexprs 只能从其他constexprs 推导出来。

标签: c++ constexpr stdmap


【解决方案1】:

不幸的是,您不能在 constexpt 上下文中使用 std::map 和 std::string。如果可能,请考虑切换到数组和字符串视图:

int main() {
  constexpr std::array my_map{
      std::pair<int, std::string_view>{ 42, "foo" },
      std::pair<int, std::string_view>{ 3, "bar" }
  };
  constexpr auto items = my_map.size();
  return items;
}

然后使用 constexpr std 算法

【讨论】:

  • 如果需要map,则可以从这个数组构造地图
【解决方案2】:

我可以在编译时推导出这张地图的size吗?

没有。由于my_map 不是编译时常量,所以不能在编译时使用。

该标准不提供编译时间图,但应该有库,或者如果你真的需要,你可以自己制作。

【讨论】:

    【解决方案3】:

    可以通过模板函数初始化地图

    template<class... Args>
    std::pair<std::integral_constant<std::size_t, sizeof...(Args)>, std::map<int, std::string>>
    make_map(Args&& ...args)
    {
        return {{}, std::map<int, std::string>({std::forward<Args>(args)...})};
    }
    
    int main() {
        const auto& p = make_map(
             std::make_pair( 42, std::string("foo") ), 
             std::make_pair( 3, std::string("bar") ) 
        );
    
        constexpr std::size_t size = std::decay_t<decltype(p.first)>::value;
        const auto& my_map = p.second;
        //or const auto my_map = std::move(p.second);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多