gpt4 book ai didi

c++ - 派生 vector : Perform operations

转载 作者:太空狗 更新时间:2023-10-29 21:24:18 26 4
gpt4 key购买 nike

我从 std::vector<int> 得到(我知道我不应该,但我只是想测试一下)。现在我可以实例化它并分配一些值:

MyVector v(5);
v[0]=3;

我什至可以返回值:

cout << v[0];

但是如果我想在类中进行一些操作,我该如何访问值呢?像这样的东西:

int func(int a){
return this->[0] + a; // EXAMPLE
}

最佳答案

如问题下的评论所述:

return (*this)[0] + a; should work. – didierc 5 hours ago

此外,由于 vector以线性方式(如数组)布置内存,您还可以通过指针访问保存值的内存,如下所示:

int *ptr = &(*this)[0];
// read an integer from the console into the 3rd element of the vector
scanf("%d", ptr + 2);

如果你有一个 vector 这会很有用字符,你需要传递一个 char*例如,字符串函数之类的东西。

但是请注意,vector<bool>行为方式不同( bool 值在内部存储在位域中,而不是 bool 数组,请参阅 http://isocpp.org/blog/2012/11/on-vectorbool )。

关于c++ - 派生 vector : Perform operations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16533976/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com