【问题标题】:enum as return type of a function in C++枚举作为 C++ 中函数的返回类型
【发布时间】:2011-11-11 15:08:24
【问题描述】:

以下 java 方法将哈希表的键作为枚举返回。

Hashtable<String, Object> props = new Hastable<String, Object>(); 

// some code here

public final Enumeration getPropertyURIs() {
    return props.keys();
}

我想将此代码翻译成 C++。

更具体地说,如何在 C++ 中实现相同的函数,该函数返回 std::map 的键枚举?

【问题讨论】:

  • 我不懂 java,但我怀疑 C++ 中的枚举与 Java 中的枚举甚至不接近。 C++ 中的enums 只是列出一些常量的一种便捷方式,为每个常量赋予一个唯一值。
  • “密钥枚举”是什么意思?在 C++ 中,map 的 key 有一个固定的类型,你只能说那个类型。 (键类型可能当然是枚举。)
  • 可能与this重复
  • @fmass:那里的解决方案适用,但问题不同。
  • 我不知道为什么要讨论 C++ enum != Java Enumeration。 Java enum 与 C++ enum 完全相同,但 Enumeration 完全不同,只是在其名称中偶然包含 3 个相同的字母。在 C++ 中,与 Enumeration 最接近的是迭代器。

标签: c++ map hashtable enumeration


【解决方案1】:

你能得到的最接近的就是返回一个迭代器。问题在于您实际上需要两个迭代器来指定范围。解决此问题的一种方法是使用输出迭代器:

template<class output_iterator_type>
void getPropertyURIs(output_iterator_type out) {
    // loop copied from @dalle
    for (props_t::const_iterator i = keys.begin(); i != keys.end(); ++i)
    {
        *out = i->first;
        ++out;
    }
}

如果您现在想将所有密钥存储在 vector 中,您可以这样做:

std::vector<std::string> keys;
getPropertyURIs(std::back_inserter(keys));

【讨论】:

    【解决方案2】:

    C++ 中的enum 只是常量的集合。

    你的意思可能是这样的吗?

    typedef std::unordered_map<std::string, boost::any> props_t;
    props_t props;
    
    std::vector<std::string> getPropertyURIs()
    {
       std::vector<std::string> keys;
       for (props_t::const_iterator i = props.begin(); i != props.end(); ++i)
       {
          keys.push_back(i->first);
       }
       return keys;
    }
    

    【讨论】:

    • 如果getPropertyURIs 将输出迭代器(其类型是模板参数`)作为输入,并在其中写入键而不是返回vector,我会更喜欢它。跨度>
    • 这可能是 OP 认为他需要的,但这种事情在 C++ 中可能是不必要的。如果您需要密钥,您只需直接遍历地图...
    • 或者使用select1st&lt;&gt;的变体调用for_each()
    • @AndréCaron:从你链接的页面:这个函数对象是一个SGI扩展;它不是 C++ 标准的一部分。
    • @BjörnPollex:我知道。这就是为什么我说...的变体。这个函数对象实现起来很简单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多