为什么我的字符串向量为空

时间:2016-04-22 15:37:10

标签: c++

我的错误是我想将directory读入字符串向量。使用memberfunction getFileList。在主要的字符串向量中迭代它是空的。我只填写一个字符串(缓冲区)来检查向量,没有列出任何文件。只有以下输出:

server_status.php

为什么?

Singleton cstr
//verify success in opening dir
opened? [0x1d92630 ]
[ buffer ]
itVect[ buffer ]

2 个答案:

答案 0 :(得分:3)

这里有一个问题:

void Singleton::buildFileList(std::vector<std::string> filesVect)

您按值传递filesVect,这意味着该功能正在使用临时功能。当函数返回时,你向向量添加项目的所有辛苦工作都会消失并消失。

通过引用传递:

void Singleton::buildFileList(std::vector<std::string>& filesVect)

这与你这样做没有什么不同:

int foo(int x)
{
   x = 10;
}

int main()
{
   int myInt = 0;
   foo(myInt);
   // myInt is still 0, not 10
}

请注意foo()按值获取int参数。尽管int更改了参数,但未对​​来电者foo()进行任何更改。

答案 1 :(得分:2)

简单的错误。不要再这样做了。参考:

变化

void buildFileList(std::vector<std::string> filesVect);

void buildFileList(std::vector<std::string>& filesVect);

同样在这里:

void Singleton::buildFileList(std::vector<std::string>& filesVect)
{
   std::vector<std::string> f;
   std::string buffer = "";
   f = openDirectory("myFiles"); // pass which dir to open
   for (auto i = f.begin(); i != f.end(); ++i) {
      if ((*i).find(".exe") != std::string::npos) {
         buffer = "myFiles/" + (*i);
         filesVect.push_back(buffer);
      }
   }
}

它有效。