【问题标题】:Adding elements into a vector using recursion使用递归将元素添加到向量中
【发布时间】:2016-06-09 20:11:12
【问题描述】:

我有一个重复添加元素的二维向量。我知道如何使用嵌套的 for 循环来做到这一点。但是,我想知道是否有办法使用递归来做到这一点?这是我使用循环的代码:

#include <vector>
#include <iomanip>
#include <iostream>

using std::cin;
using std::cout;
using std::endl;
using std::setw;
using std::vector;

int main() {
    vector<vector<int > >test;
    int items;
    cout<< "How many items" <<endl;
    cin>> items;

    for (int i = 0; i < items+1; i++) {
        vector<int> row; // Create an empty row

        for (int j = 0; j < items+1; j++) {
            row.push_back((i-1)+j); // Add an element(column) to the row
        }
        test.push_back(row);
    }

    for (int i = 1; i < items+1; i++) {
        for (int j = 1; j < items+1; j++) {
            cout << setw(4)<<test[i][j];
        }
        cout << endl;
    }
    return 0;
}

将其转换为递归函数的最有效方法是什么?

【问题讨论】:

  • 出于好奇 - 当使用循环更简单、更清晰、更好时,为什么要为此进行递归?
  • 如果你得到更高维度的向量不是更有效吗?
  • @Flux21 大多数时候你不希望有一个向量的向量。您应该使用单个向量并通过使用数学将 nD 索引转换为 1D 索引来“伪造”维度。
  • 使用递归会在堆栈帧之间复制向量时引入开销。在循环中执行此操作更有意义。
  • @tmsimont 如果您通过了参考,那么这应该不是问题。

标签: c++ recursion vector


【解决方案1】:

这里,

#include "iostream"
#include "iomanip"
#include "vector"
using namespace std;

void insert (vector < vector <int> >& my_vector, int& items, vector <int>& row, int value, int index)
{
    if (row.size()==items) // check if row is complete
    {
        my_vector.push_back(row); // add row to 2D vector
        row.clear();
        if (index<items) 
            insert(my_vector, items, row, index+1, index+1); // for next row
    }
    else // row is not complete
    {
        row.push_back(value); // add element to row
        insert(my_vector, items, row, value+1, index); // for next element
    }
}

int main()
{
    int items;
    cout << "How many items? ";
    cin >> items;
    vector < vector <int> > my_vector;
    vector <int> row;
    insert(my_vector, items, row, 1, 1);
    for (auto i: my_vector)
    {
        for (auto j: i)
            cout << setw(4) << j;
        cout << endl;
    }
}

【讨论】:

    【解决方案2】:
    #include <dirent.h> 
    #include <iostream> 
    #include <vector>
    #include <string>
    
    // Programed by Scourge
    // GNU GPLv3
    
    using std::cout;
    using std::cin;
    using std::endl;
    using std::string;
    using std::vector;
    
    // This is a good method because we can get all the files (with or without folder) recursive or not
    // from a target directory, and then have all those elements placed into a vector for easy 'for'
    // loop usage and functional parsing.
    
    vector<string> scan_dir(string scan_start, string scope, string include_folder, vector<string> &vec_track){
        
        DIR *current_dir = opendir (scan_start.c_str()); // starting dir given as a string
    
        // "dir_item" can be anything in the "current_dir" such as a new folder, file, binary, etc.
    
        while (struct dirent *dir_item_ptr = readdir(current_dir)){
            string dir_item =  (dir_item_ptr->d_name); // structure points to the getter to retrive the dir_item's name.
            if (dir_item != "." and dir_item != "./" and dir_item != ".."){
                if (dir_item_ptr->d_type == DT_DIR){
                    if(scope == "r" or scope == "-r"){
                        if(include_folder == "f" or include_folder == "-f"){
                            vec_track.push_back(dir_item);
                        }
                        scan_dir(scan_start + "/"+ dir_item, scope, include_folder, vec_track); // recursive function
                    }
                }else if(dir_item == "read"){
                    break; // full dir already read, leave the loop
                }else{
                    vec_track.push_back(dir_item);
                }
            }
        }
        return vec_track;
        closedir (current_dir); 
    }
    
    int main(){
    
        vector<string> rec_vec;
        vector<string> pwd_vec;
    
        // './' as arg 1 sets the target folder to your PWD
    
        scan_dir("./","-r","-f", rec_vec); // "scope"          = '-r' =  target_folder recursive search
        // recursive vector from pwd       // "include_folder" = '-f' = include folders in the results
    
        scan_dir("./","-n","-n", pwd_vec); // "scope"          = '-n' = use target_folder but not recursive  
        // pwd vector                      // "include_folder  = '-n' = not folder included
    
    
        for(string& i: rec_vec){cout << i << endl;} // loop through and print the vector's elements
        cout << "---------------------\n";
        for(string& i: pwd_vec){cout << i << endl;} // loop through and print the vector's elements
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      • 2014-06-03
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      相关资源
      最近更新 更多