简体   繁体   中英

Store pair values in vector C++ from a 2d vector

I've been given a 2D vector (A). I need to store values of row and column index of that vector which contains element 0.

Here is my code-

vector<pair<int,int>>v;
   for(int i=0;i<A.size();i++){
       for(int j=0;j<A[i].size();j++){
           if(A[i][j]==0){
               v.push_back(make_pair(i.first,j.second));
           }
       }
   }

But I've been getting this error

error: '__gnu_cxx::__alloc_traitsstd::allocator<std::vector<int >, std::vector >::value_type' {aka 'class std::vector'} has no member named 'first'

error: '__gnu_cxx::__alloc_traitsstd::allocator<std::vector<int >, std::vector >::value_type' {aka 'class std::vector'} has no member named 'second'

int s do not have members named first or second .

To add to the vector of pairs representing 2D indices, you simply need:

if(A[i][j]==0) {
    v.push_back({i, j});
}

While making pairs you just need to input the values into make_pair function. If you want to make a pair out of (i, j) values then you write make_pair(i,j) . To access the values you use the first and second members.

if(A[i][j] == 0){
   v.push_back(make_pair(i,j));
}

And to access these values you write v[i].first and v[i].second .

This Should Work

vector<pair<int,int>>v;
for(int i=0;i<A.size();i++){
   for(int j=0;j<A[i].size();j++){
       if(A[i][j]==0){
           v.push_back(make_pair(i,j));
       }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM