Thread: recursive vector loading

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    222

    recursive vector loading

    hi,

    I was wondering if there is a better way to do the following.

    Let say I have a recursive function rec():

    Code:
    #include <iostream>
    #include <vector>
    #include <string>
    #include <unordered_map>
    
    using namespace std;
    
    void rec(int s, vector<int>& j, unordered_map <int, int>& m){
      
      if (m[s]>0)
        rec(m[s], j, m);
      j.push_back(s);
    }
    
    
    
    int main (){
      
      vector<int> a(10);
    
      unordered_map <int, int> map;
    
      map[1] = 2;
      map[2] = 3;
      map[3] = 4;
      map[5] = 5;
    
      rec(1,a, map);
    
      for(int s = 0; s< a.size(); s++){
        cout << a[s] << "\n";
      }
    
    return 0;
    }
    and in each cycle i need to store the visited map() value. I think the code is clear what I am trying to achieve. however as a result i get:

    Code:
    0
    0
    0
    0
    0
    0
    0
    0
    0
    0
    4
    3
    2
    1
    as you can see my numbers are at the end of the vector , which is exactly a behaviour one would expect . but is there a clever way to get those numbers at the begining of the array ?? (remapping as post processing is one way to go but is there a slicker solution ??)

    thnx

    ps

    array needs to be filled with 0 apriori

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    What array are you talking about? I don't see any arrays in your code.

    If you want the values at the beginning of the vector either create an empty vector or stop using push_back() to insert records into the vector.

    Jim

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 09-22-2013, 07:00 AM
  2. Loading data into a vector from text-file
    By Niels_M in forum C++ Programming
    Replies: 3
    Last Post: 04-01-2012, 06:31 AM
  3. Replies: 1
    Last Post: 05-10-2011, 04:20 PM
  4. Opening file and loading data into Vector
    By soopah256 in forum C++ Programming
    Replies: 4
    Last Post: 08-04-2009, 10:18 PM
  5. Sorting vector via recursive functions
    By porsche911nfs in forum C++ Programming
    Replies: 18
    Last Post: 05-04-2009, 06:54 AM