从匿名命名空间为映射赋值抛出 std::bad_alloc

Assiging value to map from anonymous namespace throw std::bad_alloc

下面是错误代码 std::bad_alloc。我收到错误 行 obj_[key[i]] = value[i]; 。请帮助我修复它。

 #include<iostream>
 #include<map>
  using namespace std;

 namespace {
         const std::string key1 = "s1";
         const std::string key2 = "s2";

         const std::string value1 = "v1";
         const std::string value2= "v2";
 }

 int main()
 {

         std::string key[3] = {
                 key1, key2};
          std::string value[3] = {
                  value1,value2 };
         std::map<std::string,std::string> obj_;

         for (size_t i = 0; i < sizeof(key); ++i) { // here its thow std::bad_alloc
                 obj_[key[i]] = value[i];
            }
}

sizeof(key) 是数组的大小 字节 。不是元素的数量。

您应该使用 std::extent_v<decltype(key)>。 (需要 #include <type_traits>。)

C++17 之前的替代方案:std::extent<decltype(key)>::value。 (也需要 #include <type_traits>。)

如果这对您来说太花哨了,还有一个穷人的选择:sizeof(key)/sizeof(key[0])

或者只是硬编码 3

sizeof(key) = 96(在 os 64 位上)。要获得数组的大小,您必须将此数字除以 sizeof(std::string)(即 32(在 os 64 位上)):

for (size_t i = 0; i < sizeof(key) / sizeof(std::string); ++i) {
     obj_[key[i]] = value[i];
}

不要在此处使用 sizeof(key)

for (size_t i = 0; i <  sizeof(key); ++i) { // here its thow std::bad_alloc
        obj_[key[i]] = value[i];
    }

编辑 2018 年 8 月 21 日 使用 (sizeof(key)/sizeof(*key)) 代替:

for (size_t i = 0; i <  (sizeof(key)/sizeof(*key)); ++i) { // here its thow std::bad_alloc
        obj_[key[i]] = value[i];
    }

当您使用 sizeof() 时,它 returns size in bytes of the object, not the number of elements as you seem to be expecting. Additionally when using the operator [] you access directly the encapsulated data inside the array, with no bound check, this combination is probably your error source. You can do the math 并计算出您有多少个元素。

由于您之前知道数组大小,因此可以改用 std::array

std::array<std::string,3> key = {key1, key2, ""}; //you only used two values in your code
for (size_t i = 0; i < key.size(); ++i) {
  //your instructions
}

这有点奇怪,即使明确设置数组的大小,您仍然需要在循环中查询它的大小。假设这是您的问题陈述的意外特征,并且您事先不知道它的大小,我建议您改用 std::vector。