【问题标题】:when you push_back heap-allocated char into a vector in c++当您将堆分配的字符 push_back 放入 C++ 中的向量中时
【发布时间】:2011-07-02 19:16:34
【问题描述】:

我在将 char* 插入向量时遇到问题

当我执行以下操作时:

string str = "Hello b World d"
char *cstr, *p;
vector<char*> redn;
cstr = new char [ (str.size)+1 ];
strcpy(cstr, str.c_str());

//here I tokenize "Hello b World d"
p = strtok(cstr," ");  
while(p!=NULL){
    redn.push_back(p);
    cout << "just pushed back: " << redn.back() << endl;
    p = strtok(NULL," ");
}
delete[] cstr;

//now check

for(it= redn.begin(); it < redn.end(); it++)
     cout << *it << endl;

我得到了一个输出:

just pushed back: Hello
just pushed back: b
just pushed back: World
just pushed back: d
p0s

World
d

在我看来,*它指向了错误的东西.. 有人能告诉我发生了什么事以及如何解决这个问题吗?

【问题讨论】:

    标签: c++ vector cstring


    【解决方案1】:

    你为什么不直接使用vector&lt;std::string&gt;?它看起来像这样:

    #include <string>
    #include <sstream>
    #include <iterator>
    #include <vector>
    #include <iostream>
    
    int main() {
        std::string s = "Hello b World d";
        std::stringstream stream(s);
        std::vector<std::string> tokens(
            (std::istream_iterator<std::string>(stream)),
            (std::istream_iterator<std::string>()));
        for(std::vector<std::string>::iterator it = tokens.begin();
            it != tokens.end(); ++it)
            std::cout << *it << std::endl;
    }
    

    【讨论】:

      【解决方案2】:

      你的代码有什么问题?

      其他答案向您解释如何以更好的方式做到这一点。我的回答解释了为什么您的代码无法按预期工作,并快速修复以使其正常工作。

      附声明:

      delete[] cstr;
      

      在将对象推入向量后删除字符串,这会导致向量元素指向已被取消分配的内容。

      注释掉该行并再次检查,它会起作用。

      这是您在 Ideone 上的代码的 working sample

      在这种情况下,您的向量需要拥有删除每个包含的指向动态分配的内存空间的对象指针的所有权。

      请参阅 this 了解如何执行此操作。

      【讨论】:

      • +1 用于回答问题而不是拐弯抹角
      【解决方案3】:

      对于 STL 迭代器,使用以下语法:

      vector<char*>::iterator it;
      for(it= redn.begin(); 
          it != redn.end(); 
          ++it)
      {
         cout << *it << endl;
      }
      

      (注意 ++它提高了算法性能)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-14
        • 2021-09-27
        • 1970-01-01
        • 2019-03-11
        相关资源
        最近更新 更多