C++通过引用传递

And*_*anu 5 c++ coding-style reference depth-first-search

我最近(4天)开始学习来自C/Java背景的C++.为了学习一门新语言,我首先要重新实现不同的经典算法,尽可能使用语言.

我来到这个代码,它是一个DFS - 深度优先搜索在一个非定向图.从我读到的内容来看,最好通过C++中的引用传递参数.不幸的是,我无法完全掌握参考的概念.每次我需要一个引用时,我都会感到困惑,我认为就指针而言.在我当前的代码中,我使用pass by value.

这是代码(可能不是Cppthonic应该):

#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);
}
Run Code Online (Sandbox Code Playgroud)

您能否通过参考此代码向我提供有关如何使用引用的一些提示?

我目前的编程风格是否与C++的构造兼容?

对于C++中的二维数组,是否存在矢量和类型**的标准替代方案?

后期编辑:

好的,我已经分析了你的答案(谢谢大家),并且我以更多的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);
}
Run Code Online (Sandbox Code Playgroud)

sti*_*472 8

进入C++ 4天,你做得很好.您已经在使用标准容器,算法和编写自己的功能模板.我看到的最缺乏的东西正好是你的问题:需要传递引用/ const引用.

每次按值传递/返回C++对象时,都会调用其内容的深层副本.这根本不便宜,特别是像你的矩阵类.

首先让我们来看看showMatrix.此函数的目的是输出矩阵的内容.需要副本吗?不.是否需要更改矩阵中的任何内容?不,它的目的只是展示它.因此,我们希望通过const引用传递Matrix.

typedef vector<short> Row;
typedef vector<Row> SquareMatrix;
void showMatrix(const SquareMatrix& mat);
Run Code Online (Sandbox Code Playgroud)

[注意:我使用了一些typedef来使这更容易读写.当你有很多模板参数化时,我推荐它.

现在让我们看一下getMatrixFromFile:

SquareMatrix getMatrixFromFile(string fName);
Run Code Online (Sandbox Code Playgroud)

按值返回SquareMatrix可能很昂贵(取决于您的编译器是否对这种情况应用返回值优化),因此按值传递字符串.使用C++ 0x,我们有rvalue引用来实现它所以我们不必返回副本(我也修改了由const引用传入的字符串,原因与showMatrix相同,我们不需要副本文件名):

SquareMatrix&& getMatrixFromFile(const string& fName);
Run Code Online (Sandbox Code Playgroud)

但是,如果您没有具有这些功能的编译器,那么常见的折衷方案是通过引用传入矩阵并让函数填充它:

void getMatrixFromFile(const string& fName, SquareMatrix& out_matrix);
Run Code Online (Sandbox Code Playgroud)

这并没有为客户端提供方便的语法(现在他们必须编写两行代码而不是一行代码),但它可以一致地避免深度复制开销.还有MOJO来解决这个问题,但是C++ 0x将会过时.

一个简单的经验法则:如果您有任何用户定义的类型(不是普通的旧数据类型)并且您想将它传递给函数:

  1. 如果函数只需要从中读取,则传递const引用.
  2. 如果函数需要修改原始函数,则按引用传递.
  3. 仅当函数需要要修改的副本时才传递值.

有一些例外,你可能有一个便宜的UDT(用户定义的类型)复制比通过const引用更便宜,例如,但现在坚持这个规则,你将开始写安全的方式,高效的C++代码,不会浪费宝贵的时钟周期在不必要的副本(一个写得不好的C++程序的常见祸根).

  • 任何合理的现代编译器都将包括匿名和命名返回值优化(RVO和NRVO),因此很少有理由担心返回大值(即编译器将消除额外的复制). (2认同)