如何从C++中指向向量的指针访问向量的内容?

Pav*_*avi 53 c++ pointers vector

我有一个指向矢量的指针.现在,我如何通过指针读取向量的内容?

Seb*_*fel 77

有很多解决方案,这里有一些我想出来的:

int main(int nArgs, char ** vArgs)
{
    vector<int> *v = new vector<int>(10);
    v->at(2); //Retrieve using pointer to member
    v->operator[](2); //Retrieve using pointer to operator member
    v->size(); //Retrieve size
    vector<int> &vr = *v; //Create a reference
    vr[2]; //Normal access through reference
    delete &vr; //Delete the reference. You could do the same with
                //a pointer (but not both!)
}
Run Code Online (Sandbox Code Playgroud)

  • 我个人更喜欢`(*v)[2];`到'v-> operator [](2)`因为它更短并且仍然保留了'运算符'运算符'. (5认同)

Cha*_*had 17

像任何其他指针值一样访问它:

std::vector<int>* v = new std::vector<int>();

v->push_back(0);
v->push_back(12);
v->push_back(1);

int twelve = v->at(1);
int one = (*v)[2];

// iterate it
for(std::vector<int>::const_iterator cit = v->begin(), e = v->end; 
    cit != e;  ++cit)
{
    int value = *cit;
}

// or, more perversely
for(int x = 0; x < v->size(); ++x)
{
    int value = (*v)[x];
}

// Or -- with C++ 11 support
for(auto i : *v)
{
   int value = i;
}
Run Code Online (Sandbox Code Playgroud)


And*_*sen 16

你有一个指向矢量的指针,因为这是你编码的方式吗?您可能想重新考虑这个并使用(可能是const)引用.例如:

#include <iostream>
#include <vector>

using namespace std;

void foo(vector<int>* a)
{
    cout << a->at(0) << a->at(1) << a->at(2) << endl;
    // expected result is "123"
}

int main()
{
    vector<int> a;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);

    foo(&a);
}
Run Code Online (Sandbox Code Playgroud)

虽然这是一个有效的程序,但一般的C++样式是通过引用而不是通过指针传递向量.这将同样有效,但是您不必处理可能的空指针和内存分配/清理等.如果您不打算修改向量,请使用const引用,如果不修改向量,则使用非const引用你需要做出修改.

这是上述程序的参考版本:

#include <iostream>
#include <vector>

using namespace std;

void foo(const vector<int>& a)
{
    cout << a[0] << a[1] << a[2] << endl;
    // expected result is "123"
}

int main()
{
    vector<int> a;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);

    foo(a);
}
Run Code Online (Sandbox Code Playgroud)

如您所见,a中包含的所有信息都将传递给函数foo,但它不会复制一个全新的值,因为它是通过引用传递的.因此,它与传递指针一样有效,并且您可以将其用作普通值,而不必弄清楚如何将其用作指针或必须取消引用它.


Mar*_*som 11

vector<int> v;
v.push_back(906);
vector<int> * p = &v;
cout << (*p)[0] << endl;
Run Code Online (Sandbox Code Playgroud)


Jon*_*cto 6

您可以直接访问迭代器方法:

std::vector<int> *intVec;
std::vector<int>::iterator it;

for( it = intVec->begin(); it != intVec->end(); ++it )
{
}
Run Code Online (Sandbox Code Playgroud)

如果需要数组访问运算符,则必须取消引用指针.例如:

std::vector<int> *intVec;

int val = (*intVec)[0];
Run Code Online (Sandbox Code Playgroud)