当您在c++中将char堆分配到一个向量中时
when you push_back heap-allocated char into a vector in c++
我在将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;
}
(注意++它提高了算法性能(
相关文章:
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 为什么一个向量上的多线程操作很慢
- 将一个向量插入另一个向量的某个位置
- 将指向给定子类的指针从一个向量复制到另一个向量
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 如何在不复制的情况下将一个向量移动到另一个向量中
- 使用 std::transform 将向量向量 (a) 添加到另一个向量向量 (b)
- 如何按另一个向量的方向调整一个向量?
- 将字符向量复制到另一个向量
- 制作一对共享指针并推送一个向量
- 你能把一个向量<int64>投射到一个向量<uint8>吗
- 大家好,当一个类有一个向量作为它的数据成员时,为什么它的大小总是24?
- 为什么我们需要在优先级队列声明中添加一个向量作为参数?
- 如何将所有指针从一个向量移动到另一个向量?
- 将一个向量映射到不同的对,即使向量映射到每对时是不同的?
- 生成一个类Name_class并将两种数据类型存储在一个向量中
- 使用步骤c++构建一个向量
- 如何从另一个向量中的另一个第一元素减去向量中的第一元素
- 将一个向量对放在一个无序映射与一个映射中