将字符串的子字符串设置为向量的 char 元素时的 EXC_BAD_ACCESS (C++)
我正在尝试制作一个矢量扩展标头。其中一个函数将向量设置为控制台输入 (cin)。它使用以下代码:
vector<char> cveccin(){
string cinval;
cin>>cinval;
vector<char> creader;
for (int i=0; i<cinval.size(); i++) {
creader[i]=cinval[i];
}
return creader;
}
我在测试中使用此函数,它给了我 EXC_BAD_ACCESS。这里出了什么问题?
I am trying to make a vector extended header. One of the functions sets a vector to the console input (cin). It uses the following code:
vector<char> cveccin(){
string cinval;
cin>>cinval;
vector<char> creader;
for (int i=0; i<cinval.size(); i++) {
creader[i]=cinval[i];
}
return creader;
}
I use this function in a test, and it gives me EXC_BAD_ACCESS. What's going wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是你的向量的大小为零,并且使用 [] 不会使它变得更大。
有一条单线可以满足您的要求。
该代码创建了正确大小的向量,将 cinval 字符串复制到其中,然后从函数返回它,所有这些都在一行中完成。 C++ 是不是太棒了!
The problem is that your vector is size zero, and using [] won't make it any bigger.
There's a one-liner that does what you want.
That code creates the vector of the right size, copies the cinval string to it, and returns it from the function, all in one line. Ain't C++ marvellous!
如果要将元素添加到 std::vector 使用
要使用数组表示法,您必须首先设置 std::vector 的大小
If you want to add elements to std::vector use
To use array notation you will have to first set the size of the std::vector
问题是您创建的 creader-vector 是空的。因为它不包含任何元素,所以您无法访问或索引任何元素。要解决此问题,您可以使用 Push_back 方法而不是索引和分配。
The problem is that the creader-vector you have created is empty. Because it holds no elements, you cannot access nor index any. To fix the problem, you could for example use the push_back method instead of indexing and assigning.