C ++ follows the link

Recently (4 days) I started learning C ++ based on the background of C / Java. To learn a new language, I begin by reintegrating various classic algorithms as much as I can.

I came to this code, its DFS - Depth First Search in an undirected graph. However, from what I read, it is best to pass parameters via C ++ links. Unfortunately, I cannot fully understand the concept of a link. Every time I need a link, I get embarrassed and think in terms of pointers. In my current code, I use pass by value.

Here is the code (maybe not Cppthonic as it should):

#include <algorithm>
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
#include <vector>

using namespace std;

template <class T>
void utilShow(T elem);

template <class T>
void utilShow(T elem){
    cout << elem << " ";
}

vector< vector<short> > getMatrixFromFile(string fName);
void showMatrix(vector< vector<short> > mat);
vector<unsigned int> DFS(vector< vector<short> > mat);

/* Reads matrix from file (fName) */
vector< vector<short> > getMatrixFromFile(string fName)
{
    unsigned int mDim;
    ifstream in(fName.c_str());
    in >> mDim;
    vector< vector<short> > mat(mDim, vector<short>(mDim));
    for(int i = 0; i < mDim; ++i) {
        for(int j = 0; j < mDim; ++j) {
            in >> mat[i][j];
        }
    }
    return mat;
}

/* Output matrix to stdout */
void showMatrix(vector< vector<short> > mat){
    vector< vector<short> >::iterator row;
    for(row = mat.begin(); row < mat.end(); ++row){
        for_each((*row).begin(), (*row).end(), utilShow<short>);
        cout << endl;
    }
}

/* DFS */
vector<unsigned int> DFS(vector< vector<short> > mat){
    // Gives the order for DFS when visiting
    stack<unsigned int> nodeStack;
    // Tracks the visited nodes
    vector<bool> visited(mat.size(), false);
    vector<unsigned int> result;
    nodeStack.push(0);
    visited[0] = true;
    while(!nodeStack.empty()) {
        unsigned int cIdx = nodeStack.top();
        nodeStack.pop();
        result.push_back(cIdx);
        for(int i = 0; i < mat.size(); ++i) {
            if(1 == mat[cIdx][i] && !visited[i]) {
                nodeStack.push(i);
                visited[i] = true;
            }
        }
    }
    return result;
}

int main()
{
    vector< vector<short> > mat;
    mat = getMatrixFromFile("Ex04.in");
    vector<unsigned int> dfsResult = DFS(mat);

    cout << "Adjancency Matrix: " << endl;
    showMatrix(mat);

    cout << endl << "DFS: " << endl;
    for_each(dfsResult.begin(), dfsResult.end(), utilShow<unsigned int>);

    return (0);
}

Could you give me some tips on how to use links when referencing this code?

Is my current programming style compatible with C ++ constructs?

** ++?

LATER EDIT:

, ( ), OOP. , . const, , NULL.

:

#include <algorithm>
#include <fstream>
#include <iostream>
#include <ostream>
#include <stack>
#include <string>
#include <vector>

using namespace std;

template <class T> void showUtil(T elem);

/**
* Wrapper around a graph
**/
template <class T>
class SGraph
{
private:
    size_t nodes;
    vector<T> pmatrix;
public:
    SGraph(): nodes(0), pmatrix(0) { }
    SGraph(size_t nodes): nodes(nodes), pmatrix(nodes * nodes) { }
    // Initialize graph from file name
    SGraph(string &file_name);
    void resize(size_t new_size);
    void print();
    void DFS(vector<size_t> &results, size_t start_node);
    // Used to retrieve indexes.
    T & operator()(size_t row, size_t col) {
        return pmatrix[row * nodes + col];
    }
};

template <class T>
SGraph<T>::SGraph(string &file_name)
{
    ifstream in(file_name.c_str());
    in >> nodes;
    pmatrix = vector<T>(nodes * nodes);
    for(int i = 0; i < nodes; ++i) {
        for(int j = 0; j < nodes; ++j) {
            in >> pmatrix[i*nodes+j];
        }
    }
}

template <class T>
void SGraph<T>::resize(size_t new_size)
{
    this->pmatrix.resize(new_size * new_size);
}

template <class T>
void SGraph<T>::print()
{
    for(int i = 0; i < nodes; ++i){
        cout << pmatrix[i];
        if(i % nodes == 0){
            cout << endl;
        }
    }
}

template <class T>
void SGraph<T>::DFS(vector<size_t> &results, size_t start_node)
{
    stack<size_t> nodeStack;
    vector<bool> visited(nodes * nodes, 0);
    nodeStack.push(start_node);
    visited[start_node] = true;
    while(!nodeStack.empty()){
        size_t cIdx = nodeStack.top();
        nodeStack.pop();
        results.push_back(cIdx);
        for(int i = 0; i < nodes; ++i){
            if(pmatrix[nodes*cIdx + i] && !visited[i]){
                nodeStack.push(i);
                visited[i] = 1;
            }
        }
    }
}

template <class T>
void showUtil(T elem){
    cout << elem << " ";
}

int main(int argc, char *argv[])
{
    string file_name = "Ex04.in";
    vector<size_t> dfs_results;

    SGraph<short> g(file_name);
    g.DFS(dfs_results, 0);

    for_each(dfs_results.begin(), dfs_results.end(), showUtil<size_t>);

    return (0);
}
+5
4

4 ++ . , . , , : /.

, / ++ , . , - .

showMatrix. - . ? . - ? , - . , const.

typedef vector<short> Row;
typedef vector<Row> SquareMatrix;
void showMatrix(const SquareMatrix& mat);

[. typedef, . , ].

getMatrixFromFile:

SquareMatrix getMatrixFromFile(string fName);

SquareMatrix ( , ), . ++ 0x rvalue, , ( , const , showMatrix, ):

SquareMatrix&& getMatrixFromFile(const string& fName);

, , :

void getMatrixFromFile(const string& fName, SquareMatrix& out_matrix);

( ), . MOJO, , ++ 0x.

: ( ), :

  • const, .
  • , .
  • , .

, UDT ( ), , const, , , , ++, ( ++).

+8

, :

vector<unsigned int> DFS(vector< vector<short> > mat){

vector<unsigned int> DFS(vector<vector<short>> const &mat) { 

, const, , , / .

, , :

for_each((*row).begin(), (*row).end(), utilShow<short>);

- :

std::copy(row->begin(), row->end(), std::ostream_iterator<short>(std::cout, " "));

:

for_each(dfsResult.begin(), dfsResult.end(), utilShow<unsigned int>);

:

std::copy(dfsResult.begin(), dfsResult.end(),
          std::ostream_iterator<unsigned int>(std::cout, " "));

(... , utilShow).

2D-, ( ), :

template <class T>
class matrix { 
    std::vector<T> data_;
    size_t columns_;
public:
    matrix(size_t rows, size_t columns) : columns_(columns), data_(rows * columns)  {}

    T &operator()(size_t row, size_t column) { return data[row * columns_ + column]; }
};

, operator(), m[x][y] m(x,y), BASIC Fortran. operator[] , , , (), .

+2
void utilShow(T& elem);
vector< vector<short> > getMatrixFromFile(const string& fName);
void showMatrix(vector< vector<short> >& mat);
vector<unsigned int> DFS(vector< vector<short> >& mat);

. , , const.

++ , , . - STL. , , .

. http://msdn.microsoft.com/en-us/library/1fe2x6kt%28VS.80%29.aspx

@Jerry . , - , . C, , . , , - . , - , , , .

+1

. .

:

  • p o.
  • i - o. , .

, , .

Ptr(const T* t) Ref(const T& t).

int main() {   int a;   Ptr (& );    (); }

Ptr, t a. a. &t ( t), .

Ref, t a. a a. a &a. , ++.

. (, ):

template <class T> void utilShow(T elem) { ... }

, , t . T - , . . , "hey - , ". . ?

template <class T> void utilShow(const T &elem) { ... }

elem const, . elem, , .

, ( ), :

vector< vector<short> > getMatrixFromFile(const string &fName) { ... }
void showMatrix(const vector< vector<short> > &mat) { ... }

, : ", ! ! !" , .

:

// Don't do this!
Foo& BrokenReturnRef() {
  Foo f;
  return f;
}

int main() {
  Foo &f = BrokenReturnRef();
  cout << f.bar();
}

, ! BrokenReturnRef , f , . main f. , f, , , . ( ).

" " - , . STL operator[] .

, !:)

+1

All Articles