C++ 派生向量:执行操作
我从C++ 派生向量:执行操作,c++,vector,C++,Vector,我从std::vector(我知道我不应该,但我只是想测试它)。现在我可以实例化它并分配一些值: MyVector v(5); v[0]=3; 我甚至可以返回值: cout << v[0]; 如问题下的评论所述: 返回(*本)[0]+a;应该有效5小时前的迪迪克 此外,由于vector以线性方式(如数组)布置内存,您还可以通过指针访问保存值的内存,如下所示: int *ptr = &(*this)[0]; // read an integer from the conso
std::vector
(我知道我不应该,但我只是想测试它)。现在我可以实例化它并分配一些值:
MyVector v(5);
v[0]=3;
我甚至可以返回值:
cout << v[0];
如问题下的评论所述: 返回(*本)[0]+a;应该有效5小时前的迪迪克 此外,由于
vector
以线性方式(如数组)布置内存,您还可以通过指针访问保存值的内存,如下所示:
int *ptr = &(*this)[0];
// read an integer from the console into the 3rd element of the vector
scanf("%d", ptr + 2);
例如,如果您有一个字符的向量
,并且需要将字符*
传递给字符串函数之类的函数,那么这将非常有用
但是,请注意,
vector
的行为方式不同(布尔值在内部存储在位字段中,而不是布尔数组中,请参见) 返回(*this)[0]+a代码>应该可以工作。(*this)[0]
,this->operator[](0)
,this->at(0)
:注意最后一个做边界检查并抛出边界。@ThePhD:operator[](0)
在没有这个->
的情况下工作。非常正确,所以他有很多选择D
int *ptr = &(*this)[0];
// read an integer from the console into the 3rd element of the vector
scanf("%d", ptr + 2);