当您在c++中将char堆分配到一个向量中时

when you push_back heap-allocated char into a vector in c++

本文关键字:一个 向量 c++ 中将 char 分配      更新时间:2023-10-16

我在将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

在我看来,它指的是错误的东西。。有人能告诉我发生了什么事,我该怎么解决吗?

为什么不直接使用vector<std::string>?然后会是这样的:

#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;
}

您的代码有什么问题

其他答案会向你解释如何以更好的方式来做这件事。我的回答解释了为什么你的代码不能像你预期的那样工作,以及让它工作的快速解决方案。

附带声明:

delete[] cstr;

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

把那行注释掉,再检查一下,它会起作用的。

这是Ideone上代码的工作示例

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

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

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

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

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