Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to vector

Tags:

c++

vector

I've got this code:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector<string> *vecptr;
int veclen;

void getinput()
{
 string temp;
 for(int i = 0; i < 3; i++)
    {
     cin>>temp;
     vecptr->push_back(temp);
    }
    veclen = vecptr->size();
}


int main()
{
 getinput();

    for(int i = 0; i < veclen; i++)
    {
     cout<<vecptr[i]<<endl;
    }

 return 0;
}

My compiler(G++) throw me some errors: test2.cpp:28:17: error: no match for 'operator<<' in 'std::cout << *(vecptr + ((unsigned int)(((unsigned int)i) * 12u)))' ...

What's wrong? What can I do to fix it?

like image 389
icepopo Avatar asked Nov 24 '11 19:11

icepopo


People also ask

Can you have a pointer to a vector?

You can store pointers in a vector just like you would anything else. Declare a vector of pointers like this: vector<MyClass*> vec; The important thing to remember is that a vector stores values without regard for what those values represent.

Can you use pointers with vectors in C++?

Similar to any other vector declaration we can declare a vector of pointers. In C++ we can declare vector pointers using 3 methods: Using std::vector container.

How do you iterate through a vector of pointers?

Use a for loop and reference pointer In C++ , vectors can be indexed with []operator , similar to arrays. To iterate through the vector, run a for loop from i = 0 to i = vec. size() .

What does vector data () do?

vector data() function in C++ STL The std::vector::data() is an STL in C++ which returns a direct pointer to the memory array used internally by the vector to store its owned elements.


1 Answers

The program is still not completely right. You have to initialize the vector pointer and then give it a size and the use it. A full working code could be,

#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector<string> *vecptr = new vector<string>(10);
int veclen;

void getinput()
{
 string temp;
 for(int i = 0; i < 3; i++)
    {
     cin>>temp;
     (*vecptr)[i] = temp;
    }
    veclen = (*vecptr).size();
}


int main()
{
 getinput();

    for(int i = 0; i < veclen; i++)
    {
     cout<<(*vecptr)[i]<<endl;
    }

 return 0;
}

Although I have mentioned the size as 10 you could make it a variant.

like image 161
Ajai Avatar answered Oct 11 '22 15:10

Ajai