简体   繁体   English

C++ 向量循环和 push_back 问题?

[英]C++ Vector Loop and push_back problem?

I could not figure out what went wrong when I tried to modify vector array.当我尝试修改向量数组时,我无法弄清楚出了什么问题。 Here is my vector array:这是我的向量数组:

14248 DL AAAAA
14248 DL AAAAA
14248 DL AAAAA
14248 DL AAAAA
14248
14248
14248
14248

What I want to try to do here is, if vector string contains "AAAAA" I will push back as "-" to different vector cRntiModDash.我想在这里尝试做的是,如果向量字符串包含“AAAAA”,我将作为“-”推回不同的向量 cRntiModDash。 If NOT "AAAAA", then I push back original string.如果不是“AAAAA”,那么我会推回原始字符串。

So, the cRntiModDash vector should be contained after modified:因此,修改后应包含 cRntiModDash 向量:

-
-
-
-
-
14248
14248
14248
14248
14248

This is what I want, but when I push back to multi-vector all, then something wrong and caused the exit.这就是我想要的,但是当我全部推回多向量时,出现问题并导致退出。

std::vector<std::vector<string>*> all;
vector<std::string> cRntiModDash;                   
for (vector < string >::iterator ct(cRnti.begin()); ct != cRnti.end(); ct++)
{ 
    std::string cRntTmp (*ct);
    if (cRntTmp.find("AAAAA") != string::npos)
        cRntiModDash.push_back("-");
    else
        cRntiModDash.push_back(*ct);
    }
}
all.push_back(&cRntiModDash);


for (unsigned int j = 0; j < cRnti.size(); j++)
{
  for (std::vector<std::vector<string>*>::iterator i = all.begin(); i != all.end(); i++)
  {
      if (i != all.begin()) 
      {
         CSVToFile << ",";
         std::cout<< ",";
      }
    std::cout<< (**i)[j];
    CSVToFile <<(**i)[j];
  }
  std::cout<< std::endl;
  CSVToFile << std::endl;
}
CSVToFile.close();

If I don't modify vector cRnti, then it is OK.如果我不修改vector cRnti,那就可以了。 I had checked my modified vector did not have any spaces.我检查了我修改后的向量没有任何空格。 If someone can recognize my problem, I am really appreciate.如果有人能认识到我的问题,我真的很感激。 I had been tried for while but could not see the problem.我已经尝试了一段时间,但看不到问题所在。 Thanks in advance.提前致谢。

vector<std::string> cRntiModDash;                   
// ...
all.push_back(&cRntiModDash);

You store a pointer to the (presumably) local variable cRntiModDash in all .您将指向(可能)局部变量cRntiModDash的指针存储在all中。 As soon as cRntiModDash goes out of scope, all will contain a pointer to a not longer valid object.一旦cRntiModDash离开 scope, all将包含一个指向不再有效的 object 的指针。 That memory location will be reused by other variables and anything might happen when you try to access the vectors in all later on. memory 位置将被其他变量重用,当您稍后尝试访问all向量时,可能会发生任何事情。

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

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