access to a vector witout ->at() function;

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
Ultras
New poster
Posts: 3
Joined: Fri Aug 18, 2006 9:37 pm

access to a vector witout ->at() function;

Post by Ultras »

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.
mf
Guru
Posts: 1244
Joined: Mon Feb 28, 2005 4:51 am
Location: Zürich, Switzerland
Contact:

Post by mf »

You can use cout<<(*v)[2], or:

Code: Select all

void myFunction(vector<int> &v){
   cout<<v.at(2);
   cout<<v[2];
} 
Ultras
New poster
Posts: 3
Joined: Fri Aug 18, 2006 9:37 pm

Post by Ultras »

cout<<(*v)[2]
its working thanks.
but cout<<v[2] is not.
Moha
Experienced poster
Posts: 216
Joined: Tue Aug 31, 2004 1:02 am
Location: Tehran
Contact:

Post by Moha »

at function is slow! because it checkes the index! use iterators or [] instead
Martin Macko
A great helper
Posts: 481
Joined: Sun Jun 19, 2005 1:18 am
Location: European Union (Slovak Republic)

Post by Martin Macko »

Ultras wrote:cout<<(*v)[2]
its working thanks.
but cout<<v[2] is not.
Note the 'reference to' symbol & in mf's code. If you replace the 'poiner to' symbol * by 'reference to' symbol, the expression cout<<v[2] will work.
Quantris
Learning poster
Posts: 80
Joined: Sat Dec 27, 2003 4:49 am
Location: Edmonton AB Canada

Post by Quantris »

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 ;) )
Post Reply

Return to “C++”