Hi all.
For example we have:
#include <iostream>
#include <vector>
using namespace std;
void myFunction(vector<int> *v);
int main(void){
vector<int> a;
a.push_back(10);
a.push_back(20);
a.push_back(30);
a.push_back(40);
myFunction(&a);
system("PAUSE");
}
void myFunction(vector<int> *v){
cout<<v->at(2); //will work but we cant use it...
cout<<v[2]; //error.
cout<<*v[2]; //error.
}
The question is how we can get acces to the elements of the vector *v ?
Using of iterators will be too slow in case of big vector.
Any other ways to solve it?
PS: is "->at()" function using iterators i.e its not a random acces DS.
access to a vector witout ->at() function;
Moderator: Board moderators
You can use cout<<(*v)[2], or:
Code: Select all
void myFunction(vector<int> &v){
cout<<v.at(2);
cout<<v[2];
}
-
- A great helper
- Posts: 481
- Joined: Sun Jun 19, 2005 1:18 am
- Location: European Union (Slovak Republic)
I think v->operator[](2) works too (but it's somewhat ugly).
I'm not sure what you mean when you say iterators are slow, because something like *(v->begin() + 2) is still constant-time.
I do prefer the pass-by-reference method here though - don't use a pointer unless there is a specific reason to (especially if you don't understand how pointers work
)
I'm not sure what you mean when you say iterators are slow, because something like *(v->begin() + 2) is still constant-time.
I do prefer the pass-by-reference method here though - don't use a pointer unless there is a specific reason to (especially if you don't understand how pointers work
