我从 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/