+ 2

how to iterate through a vector of type std: :pair

i have a vector std: :vector<std::pair<int,int>> k; how could i iterate through this vector. k. begin is giving error. Although k. begin->first is giving correct value. but i want to iterate through all elements, how could i do this.

6th Mar 2018, 8:02 AM
shobhit
shobhit - avatar
3 Réponses
+ 11
You would iterate through it like any other vector. Either by using an iterator of the correct type (e.g std::vector<std::pair<int,int>>::iterator) or a range based loop with the auto keyword. See: https://www.sololearn.com/learn/261/?ref=app for more info Here is an example: https://code.sololearn.com/cDOYsqXbSQQb/?ref=app Note: I have used const iterators as no values are to be changed in the example code I provided. This document may also assist in your understanding of iteration/iterators https://www.cprogramming.com/tutorial/stl/iterators.html
6th Mar 2018, 8:10 AM
jay
jay - avatar
+ 7
NOTE : pair and vector are 2 different things. Pair is a container just like vector is. You need to use this class methods.. Take a pair singularly.. std::pair<T,U> myPair; //T and U can be same type myPair.makepair(a,b); //a single pair c=myPair.first; d=myPair.second; Pair<int,int> pairArray[5]; .... vector<pair<int,int>> myV; for (int i = 0 .....) myV.push_back(make_pair(arr1[i],arr2[I])); for (int i ... ) cout<< myV[i].first << '-' << myV[i].second;
6th Mar 2018, 8:50 AM
AZTECCO
AZTECCO - avatar