Search code examples
c++vectortypedef

How to have access using pointers on two type definition vectors


I'm trying to learn how I can use the different typedef vector, and after creating them how I can access the variables. I have commented as I wrote the code

  #include <iostream> 
    #include <vector>
    //#include <stdlib.h>
    
    using namespace std; 
    
    
    //Here I wanted to created a structure where I have position vector  
    struct Point { 
        double  pos;
    }; 
      
    // now I have the type  vector definitons  named List
    typedef std::vector<Point> List;
    
    
    int main() 
    { 
    
    //I have initialized two list which are List A, and List B 
    List A;
    List B;
    
    //Point a, and Point b are two double data type variables that I want to push back into the two kind of list
    Point a;
    Point b;
    for(int i =0; i<100; i ++){
    a.pos = 2*i+1;
    b.pos = 2*i -1;
    
      A.push_back(a);
      B.push_back(b);
    }  
        return 0; 
    } 

Now my question is how I can access the variables from the two List that I have created. I want to have access to the same index vector.

This is how I tried with dereferencing the pointer, but I think I'm making some mistakes:

 for (List::iterator it = A->begin(); it != A->end(); it++) {
     Point* val = &(*it);
     cout <<  val->pos()<<endl; 
     
     //I need to access the  value from B list too
  }

Solution

  • Here is the code that would work (assuming A and B are the same length):

    size_t jj = 0;
    for (List::iterator it = A.begin(); it != A.end(); it++) {
        cout <<  it->pos<<endl; 
        cout << (B.begin() + jj)->pos<< endl;
        jj++;
    }
    

    Note that A and B are not pointers so you access their methods normally. By the way, if you have access to C++11 and above, you can use the following:

    size_t ii = 0;
    for (const auto& el: A) {
       cout << el.pos << "," << B.at(ii).pos << endl;
       ii++;
    }