繁体   English   中英

插入unordered_set失败

[英]Insert into an unordered_set failed

首先,这不是我自己的代码! 它取自Google的Android源代码https://android.googlesource.com/platform/art/+/android-9.0.0_r10/tools/hiddenapi/hiddenapi.cc因此, 应该对其进行测试并且应该可以工作! 但是,它在“插入...”点失败短代码:

/*...*/
std::unordered_set<std::string> light_greylist_;
/*...*/

/*Caller:*/ OpenApiFile(light_greylist_path_, &light_greylist_);

bool OpenApiFile(const std::string& path, std::unordered_set<std::string>* list) {

  std::ifstream api_file(path, std::ifstream::in);

  for (std::string line; std::getline(api_file, line);) {
/* line IS filled; I've checked it with a simple fprintf(): [this IS my code for testing]*/
    FILE *stream = fopen("test.txt", "a+");
    fprintf(stream, "%s\n", line.c_str());
    fclose(stream);

/* This is the point where it crashes with an "Illegal instruction (core dumped)"*/
    list->insert(line);
  }

  api_file.close();
  return true;
}

怎么了?

我将list作为参考而不是指针。 很难说为什么原始代码使用指针,因为如果用NULL调用它很可能会崩溃。 还要检查文件是否已成功打开(即使这次似乎已经成功打开了文件)。

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <unordered_set>

bool OpenApiFile(const std::string& path, std::unordered_set<std::string>& list) {

  std::ifstream api_file(path, std::ifstream::in);
  if (!api_file) {
    return false;
  }

  for (std::string line; std::getline(api_file, line);) {
    list.insert(line);
  }

  return true;
}

int main(int argc, char* argv[]) {
  std::vector<std::string> files(argv+1, argv+argc);

  for(auto& light_greylist_path_ : files) {
    std::unordered_set<std::string> light_greylist_;

    if (OpenApiFile(light_greylist_path_, light_greylist_) == false) {
      std::cerr << "failed opening "+light_greylist_path_+"\n";
    } else {
      for(auto& lg : light_greylist_) {
        std::cout << lg << "\n";
      }
    }
  }
  return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM