将strcpy与std::vector一起使用
Using strcpy with std::vector
我在将strcpy
与自己类的实例的vector
一起使用时遇到了一些问题。这是课程:
class elemente {
char name[5];
short val;
bool red;
};
所以,我从这个类中制作了一个向量:
vector<elemente> ele(1);
但如果我尝试进行此操作:
strcpy(ele.back().name, strtok(line, " "));
我总是有"分段错误"。为什么?
我使用GDB调试我的程序,line
变量是正确的,而且如果我用普通的char *
替换向量,一切都很好(程序不起作用,但内容很好)。
我能做什么?
由于您使用的是C++,因此应该使用该语言提供的功能,而不是使用C风格的代码。很好,您决定使用std::vector
,所以继续使用std::string
来存储字符串,使用std::istringstream
来创建一个输入流,从中读取令牌,并使用std::getline
来实际检索这些令牌。
首先,使用访问说明符public
使elemente
类的属性在此类的范围之外可用,并将name
的类型更改为std::string
:
class elemente
{
public:
std::string name;
// ...
};
然后从行中检索令牌可能如下所示:
#include <iostream>
#include <vector>
#include <sstream>
...
std::vector<elemente> elements;
std::string line("this is my input line");
std::istringstream lineStream(line);
for (std::string word; std::getline(lineStream, word, ' '); )
{
if (!word.empty())
{
elements.push_back(elemente());
elements.back().name = word;
}
}
为了测试这个代码,您只需打印存储在这个向量的元素中的所有名称:
std::vector<elemente>::iterator e;
for(e = elements.begin(); e != elements.end(); ++e)
std::cout << e->name << ".";
输出:
this.is.my.input.line.
或者,你可以创建一个类的公共构造函数,这样你就可以用正确初始化的成员来构造元素:
class elemente
{
public:
elemente(const std::string& s) : name(s){ }
// ...
std::string name;
// ...
};
然后,令牌的解析将变成:
for (std::string word; std::getline(lineStream, word, ' '); )
{
if (!word.empty())
elements.push_back(elemente(word));
}
希望这有帮助:)
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 如何将AERT_Allocate与 std:vector 一起使用
- 将用户定义的类型与 std::vector 和 std::sort 一起使用
- 我不能将 'fill' std::vector 构造函数与 unique_ptrs 一起使用
- 为什么 std::foreach 不能与 std::vector 一起使用<bool>?
- 使用 std::vector<Particle> 粒子;函数 .at() 不能与迭代器一起使用,它作为 for 循环中的参数
- 将 std::vector emplace_back() 与 std::p air 一起使用,并带有构造函数初始值设定项
- 是否可以重载模板函数以与 std::vector 的元素一起使用
- <vector> 与 cin 和 for() 循环C++一起使用
- 将make_move_iterator与vector::insert一起应用有意义吗?(C++)
- 如何将 std::vector::emplace_back 与 vector<int><vector> 一起使用?
- 将 std::vector 与类元素一起使用时出现内存泄漏
- 将 std::vector 与结构一起使用时出现不完整的类型错误
- 将std::vector与std::thread一起使用
- 将Vector与类一起使用时没有运算符错误
- 如何将 Vector<T>::reverse_iterator 与一个元素一起使用
- 将自定义类与向量一起使用:'std::vector'默认构造函数错误
- 如何在 C++11 中将 vector 与引用类型实例对象一起使用
- 如何访问 std::vector 的内部连续缓冲区,是否可以将其与 memcpy 等一起使用
- 将strcpy与std::vector一起使用