使用数组作为地图密钥不使用C 11编译器命令



我需要使用数组作为地图密钥,但是我收到编译器错误,表明映射声明未命名类型。

我在类似的问题中使用代码,但是即使我选择了-std = c 0x或-std = c 11编译器命令。

,该代码也不会编译。

我使用的代码是:

typedef std::array<unsigned int, 3> alphabet;
std::map<alphabet, std::string> dictionary;
dictionary[{{1, 0, 8}}] = "hello";

错误是:

错误:'dictionary'不命名类型|错误:预期 在']'''|| ===构建完成:2个错误,0 警告(0分钟1秒)=== |

即使在搜索Google时,我也看不到这个主题。我正在使用CodeBlocks作为我的IDE,并选择了上面提到的编译器命令。

我认为错误可能是因为您试图在文件范围中分配给dictionary。正如指出的那样,变量应在全局范围中初始化,即:

std::map<alphabet, std::string> dictionary = { {{1,0,8}, "hello"} };

否则,您应该将其放在块范围中,即在main()中。

#include <array>
#include <map>
typedef std::array<unsigned int, 3> alphabet;
std::map<alphabet, std::string> dictionary;
int main()
{
  dictionary[{{1, 0, 8}}] = "hello";
}

作为旁注,似乎可以将牙套伸出。您不需要两组括号。dictionary[{1, 0, 8}]就足够了。

如何比较地图排序的数组?

我想您应该提供这样的比较方法:

struct ltarray
{
  bool operator()(const alphabet& s1, const alphabet& s2) const
  {
    //how you compare???
    return (s1<s2);
  }
};

您需要使用比较方法来启动地图模板:

std::map<alphabet, std::string, ltarray> dictionary;

最新更新