Click here to Skip to main content
15,167,677 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a vector like this :
vector < pair < int, pair < int,int > > > v
I want to access all the three elements . How can i do that through iterator?

What I have tried:

I looked for the possible answers on the internet but cannot get any satisfactory answer. I tried iterator like this :
vector < pair < int,pair <int,int> > > v;
vector < pair < int,pair <int,int> > > :: iterator it=v.begin();
cout<<it->first->second;
Its not working
Posted
Updated 9-Jun-21 14:39pm
v3
Comments
CPallini 6-Jul-16 7:01am
   
As far as I know your declaration of v is not valid.
Member 12621273 6-Jul-16 7:06am
   
i have corrected it now
Philippe Mori 6-Jul-16 15:17pm
   
Obviously, since the second pair is a value, last arrow should be replaced by a dot.

A vector only accepts one Type in its implementation, so you cannot have <int, pair>. You need to create a new class, or use a pair that also contains a pair; something like:
C++
vector<pair<int, pair<int, int > > > v;
pair<int, int> p;
pair<int, pair< int, int> > q;
p.first = 1;
p.second = 2;
q.first = 1;
q.second = p;
v.push_back(q);

p.first = 3;
p.second = 4;
q.first = 2;
q.second = p;
v.push_back(q);
for (vector<pair<int, pair<int, int > > >::iterator it = v.begin(); it < v.end(); ++it)
{
    q = *it;
    int num = q.first;
    p = q.second;
    cout << num << " : " << p.first << " - " << p.second << endl;
}
   
v3
Comments
Member 12621273 6-Jul-16 7:13am
   
I have corrected it now
Richard MacCutchan 6-Jul-16 7:21am
   
So is it working or do you still have a problem?
Member 12621273 6-Jul-16 7:26am
   
i still have same problem
Richard MacCutchan 6-Jul-16 7:33am
   
See updated solution.
you do like this,
vector <pair <int,="" pair="" int=""> > > v;
INSERION OF VALUES:
v.push_back(make_pair(a, make_pair(b, c)));
ACCESSING VALUES:
a = v[i].first;
b = v[i].second.first;
c = v[i].second.second;
   
C++
// I have a vector like this :
vector < pair < int, pair < int, int > > > v;
//	I want to access all the three elements.How can i do that through iterator ?

pair < int, int > p1(1,2);
pair < int, pair < int, int > > p2(3, p1);

v.push_back(p2);

for (auto it : v) {
	cout << ">" << "; " << it.first << "; " << it.second.first << "; " << it.second.second << "\n";
	}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900