【问题标题】:How to read dictionary file to a map<char, vector<bool> >?如何将字典文件读入 map<char, vector<bool>>?
【发布时间】:2021-02-14 05:25:20
【问题描述】:

我有一个文本文件,它是一对“字符-二进制代码”的字典。我需要从文件中读取该字典并将值放入 map 以对其执行一些其他操作。 我决定先分别读取每一行(因为二进制代码是可变长度的),然后我需要将每个字符分配给映射的第一个成员(char),将二进制代码分配给第二部分(布尔向量)

我的字典文件:

'0111010
,110110
.11110101
:110101011
;111101000
A0011010
B01110011
I0011011
S01110110
T0111000
W01110111
Y111101001
a0000
b1111011

我的代码:

    vector<bool> CharCode;
    char key;
    char code;
    string str;
    map<char, vector<bool> > dict;//associative array of charater and its binary code

    ifstream Dictionary(Dict);

    while (getline(Dictionary, str)) 
    {
        std::cout << str << "\n";
        //But how to put the key and code to char and vector<bool> respectively?

    }

    Dictionary.close();

【问题讨论】:

  • 您可以使用map[key] = value assignments 来填充地图。
  • @UlrichEckhardt 但该值不是一个简单的变量,它是一个向量。我觉得我不会工作
  • @brc-dd 非常感谢!现在我明白了

标签: c++ dictionary vector


【解决方案1】:

我认为这么多代码就足够了:

// include necessary files
#include <algorithm> // for std::copy
#include <fstream>   // for std::ifstream
#include <iostream>  // for std::cout
#include <iterator>  // for std::ostream_iterator
#include <map>       // for std::map
#include <string>    // for std::string
#include <vector>    // for std::vector

// function to convert string containing 0s and 1s
// to std::vector<bool> https://stackoverflow.com/a/27367542
auto str_to_vec(std::string &&s) {

  // declare vector to return, and later insert into dictionary
  std::vector<bool> v;

  // extract characters from the string repeatedly
  // https://en.cppreference.com/w/cpp/language/range-for
  for (auto ch : s)

    // push true in vector if character is '1' else false, I've
    // ignored checking if the string contains only 0s and 1s,
    // you may wish to add a validation check for that yourself
    v.push_back(ch == '1');

  // return the constructed vector
  return v;
}

// driver function
int main() {

  // open your file, replace filename with your dictionary file
  std::ifstream fin("my_dict.txt");

  // declare your dictionary
  std::map<char, std::vector<bool>> dict;

  // extract strings from the file repeatedly
  for (std::string str; fin >> str;)

    // check if length of string is atleast 2 you may skip this
    // if already guaranteed
    if (str.length() > 1)

      // https://en.cppreference.com/w/cpp/container/map/operator_at
      dict[str[0]] = str_to_vec(str.substr(1));

  // now do something with your dictionary here
  for (auto &&[ch, v] : dict) {
    std::cout << '\n' << ch << " : ";
    std::copy(v.begin(), v.end(),
              std::ostream_iterator<bool>(std::cout, ""));
  }
}

示例运行:https://wandbox.org/permlink/1fi756kz8grmNPf6

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多