C++ 通过引用传递 Vector 字符指针

标签 c++ reference vector chat constants

大家好,我遇到了以下问题,我需要从文件构建 vector 数组。 我设法通过将文件读入字符串缓冲区然后将其保存到以下 vector 中来创建 vector 。

vector<char> pattern(contents.begin(), contents.end());

但是我需要将 vector 传递给以下函数。

void WuManber::Initialize( const vector<const char *> &patterns, 
                      bool bCaseSensitive, bool bIncludeSpecialCharacters, bool bIncludeExtendedAscii )

我如何从文件中读取该函数的可传递 vector 。 谢谢你的帮助。

为了详细说明,我需要它来执行以下操作

for ( size_t q = m; q >= B; --q ) 
  { // start loop -8-

  unsigned int hash;
  hash  = m_lu[patterns[j][q - 2 - 1]].offset; // bring in offsets of X in pattern j
  hash <<= m_nBitsInShift;
  hash += m_lu[patterns[j][q - 1 - 1]].offset;
  hash <<= m_nBitsInShift;
  hash += m_lu[patterns[j][q     - 1]].offset;
  size_t shiftlen = m - q;
  m_ShiftTable[ hash ] = min( m_ShiftTable[ hash ], shiftlen );
  if ( 0 == shiftlen ) 
 {  // start if -8-
    m_PatternMapElement.ix = j;
    m_PatternMapElement.PrefixHash = m_lu[patterns[j][0]].offset;
    m_PatternMapElement.PrefixHash <<= m_nBitsInShift;
    m_PatternMapElement.PrefixHash += m_lu[patterns[j][1]].offset;
    m_vPatternMap[ hash ].push_back( m_PatternMapElement );
  } // end if -8-

int main(int argc, char* argv[])
{
if (argc < 2) {
  std::cout << "usage: " << argv[0] << " <filename>\n";
  return 2;
 }

 ifstream fin(argv[1]);
 if (fin) {
  stringstream ss;
  // this copies the entire contents of the file into the string stream
  ss << fin.rdbuf();
  // get the string out of the string stream
  string contents = ss.str();
  cout << contents;
  // construct the vector from the string.
  vector<char> pattern(contents.begin(), contents.end());
  Initialize( &pattern);
  cout << pattern.size();
 }
 else {
  cout << "Couldn't open " << argv[1] << "\n";
  return 1;
 }
 return 0;
}

最佳答案

函数正在寻找 vector C 字符串(这是 const char * 在名为 patterns 的容器中最可能的含义。

以下是构建一个的方法:

std::vector<const char*> patterns;
patterns.push_back("my-first-pattern");
patterns.push_back("my-second-pattern");

如果您或您的团队设计了此功能,您可能希望建议将容器类型更改为更接近 C++ 的类型 vector<string> .

如果您从文件中读取模式,您可以按如下方式填充数组:

编辑(回应评论)

std::ifstream ifs("file_with_patterns.txt");
std::vector<const char*> patterns;
while (!ifs.eof()) {
    std::string buf;
    std::getline(ifs, buf);
    patterns.push_back(strdup(buf.c_str()));
}

关于C++ 通过引用传递 Vector 字符指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9434633/

相关文章:

c++ - 将 QObject 指针从 QML 对象传递到 C++

c++ - 二叉搜索树 - 复制树

c++ - 为什么双引用值在分配给 C++ 中的 float 变量时不会改变

c++ - 二维世界速度到二维局部速度

c++ - 获取 vector 的总和

C++ 如何将 wchar_t* 转换为 TCHAR [](不是 TCHAR*)

C++ 枚举与 C# 一样的属性

javascript - tmpl 未定义 jquery.slider.js

PHP 引用(& 符号)

python - 将三角矩阵的元素放入向量中