将字符串的子字符串设置为向量的 char 元素时的 EXC_BAD_ACCESS (C++)

发布于 2024-11-28 05:30:08 字数 337 浏览 2 评论 0原文

我正在尝试制作一个矢量扩展标头。其中一个函数将向量设置为控制台输入 (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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小…楫夜泊 2024-12-05 05:30:08

问题是你的向量的大小为零,并且使用 [] 不会使它变得更大。

有一条单线可以满足您的要求。

vector<char> cveccin()
{
    string cinval;
    cin >> cinval;
    return vector<char>(cinval.begin(), cinval.end());
}

该代码创建了正确大小的向量,将 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.

vector<char> cveccin()
{
    string cinval;
    cin >> cinval;
    return vector<char>(cinval.begin(), cinval.end());
}

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!

梦年海沫深 2024-12-05 05:30:08

如果要将元素添加到 std::vector 使用

vector<char> creader;
creader.push_back( var );

要使用数组表示法,您必须首先设置 std::vector 的大小

vector<char> creader;
creader.resize ( 10 );
creader[0] = var1;
creader[1] = var2;

If you want to add elements to std::vector use

vector<char> creader;
creader.push_back( var );

To use array notation you will have to first set the size of the std::vector

vector<char> creader;
creader.resize ( 10 );
creader[0] = var1;
creader[1] = var2;
孤星 2024-12-05 05:30:08

问题是您创建的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文