- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我最近(4 天)开始学习来自 C/Java 背景的 C++。为了学习一门新语言,我通常会从重新实现不同的经典算法开始,尽可能地针对特定语言。
我来到这段代码,它是一个 DFS - 无向图中的深度优先搜索。从我读到的内容来看,最好在 C++ 中通过引用传递参数。不幸的是,我不能完全理解引用的概念。每次我需要引用时,我都会感到困惑,我会根据指针来思考。在我当前的代码中,我使用按值传递。
这是代码(可能不是它应该的 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);
}
您能否通过引用这段代码给我一些关于如何使用引用的提示?
我当前的编程风格是否与 C++ 的结构兼容?
对于 C++ 中的二维数组,是否有一个标准的替代 vector 和类型**?
后期编辑:
好的,我已经分析了您的答案(谢谢大家),并且以更面向对象的方式重写了代码。我也了解什么是引用并打算使用它。它有点类似于 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);
}
最佳答案
在 C++ 的 4 天里,您做得很好。您已经在使用标准容器、算法并编写自己的函数模板。我看到的最缺乏的东西正是关于你的问题:需要通过引用/const 引用传递。
任何时候按值传递/返回 C++ 对象,都在调用其内容的深层拷贝。这一点都不便宜,尤其是对于像矩阵类这样的东西。
首先让我们看看 showMatrix。这个函数的目的是输出一个矩阵的内容。它需要拷贝吗?不,它需要改变矩阵中的任何东西吗?不,它的目的只是为了展示它。因此我们想通过 const 引用传递 Matrix。
typedef vector<short> Row;
typedef vector<Row> SquareMatrix;
void showMatrix(const SquareMatrix& mat);
[注意:我使用了一些 typedef 来使它更易于阅读和编写。当你有很多模板参数化时,我推荐它]。
现在让我们看看 getMatrixFromFile:
SquareMatrix getMatrixFromFile(string fName);
此处按值返回 SquareMatrix 可能代价高昂(取决于您的编译器是否对这种情况应用返回值优化),按值传递字符串也是如此。使用 C++0x,我们有右值引用来创建它,因此我们不必返回拷贝(出于与 showMatrix 相同的原因,我还修改了要通过 const 引用传入的字符串,我们不需要拷贝文件名):
SquareMatrix&& getMatrixFromFile(const string& fName);
但是,如果您没有具有这些功能的编译器,那么一个常见的折衷方案是通过引用传入矩阵并让函数填充它:
void getMatrixFromFile(const string& fName, SquareMatrix& out_matrix);
这并没有为客户端提供方便的语法(现在他们必须编写两行代码而不是一行),但它始终如一地避免了深度复制开销。还有MOJO来解决这个问题,但这将在 C++0x 中过时。
一个简单的经验法则:如果你有任何用户定义的类型(不是普通的旧数据类型)并且你想将它传递给函数:
有一些异常(exception)情况,例如,您可能拥有廉价的 UDT(用户定义类型),它的复制成本低于通过 const 引用传递的成本,但是现在坚持这条规则,您将继续前进编写安全、高效的 C++ 代码,不会在不必要的拷贝上浪费宝贵的时钟周期(编写糟糕的 C++ 程序的常见祸根)。
关于C++ 通过引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3133909/
Github:https://github.com/jjvang/PassIntentDemo 我一直在关注有关按 Intent 传递对象的教程:https://www.javacodegeeks.c
我有一个 View ,其中包含自动生成的 text 类型的 input 框。当我单击“通过电子邮件发送结果”按钮时,代码会将您带到 CalculatedResults Controller 中的 Em
我有一个基本的docker镜像,我将以此为基础构建自己的镜像。我没有基础镜像的Dockerfile。 基本上,基本镜像使用两个--env arg,一个接受其许可证,一个选择在容器中激活哪个框架。我可以
假设我想计算 2^n 的总和,n 范围从 0 到 100。我可以编写以下内容: seq { 0 .. 100 } |> Seq.sumBy ((**) 2I) 但是,这与 (*) 或其他运算符/函数不
我有这个网址: http://www.example.com/get_url.php?ID=100&Link=http://www.test.com/page.php?l=1&m=7 当我打印 $_G
我想将 window.URL.createObjectURL(file) 创建的地址传递给 dancer.js 但我得到 GET blob:http%3A//localhost/b847c5cd-aa
我想知道如何将 typedef 传递给函数。例如: typedef int box[3][3]; box empty, *board[3][3]; 我如何将 board 传递给函数?我
我正在将一些代码从我的 Controller 移动到核心数据应用程序中的模型。 我编写了一个方法,该方法为我定期发出的特定获取请求返回 NSManagedObjectID。 + (NSManagedO
为什么我不能将类型化数组传递到采用 any[] 的函数/构造函数中? typedArray = new MyType[ ... ]; items = new ko.observableArray(ty
我是一名新的 Web 开发人员,正在学习 html5 和 javascript。 我有一个带有“选项卡”的网页,可以使网页的某些部分消失并重新出现。 链接如下: HOME 和 JavaScript 函
我试图将对函数的引用作为参数传递 很难解释 我会写一些伪代码示例 (calling function) function(hello()); function(pass) { if this =
我在尝试调用我正在创建的 C# 项目中的函数时遇到以下错误: System.Runtime.InteropServices.COMException: Operation is not allowed
使用 ksh。尝试重用当前脚本而不修改它,基本上可以归结为如下内容: `expr 5 $1 $2` 如何将乘法命令 (*) 作为参数 $1 传递? 我首先尝试使用“*”,甚至是\*,但没有用。我尝试
我一直在研究“Play for Java”这本书,这本书非常棒。我对 Java 还是很陌生,但我一直在关注这些示例,我有点卡在第 3 章上了。可以在此处找到代码:Play for Java on Gi
我知道 Javascript 中的对象是通过引用复制/传递的。但是函数呢? 当我跳到一些令人困惑的地方时,我正在尝试这段代码。这是代码片段: x = function() { console.log(
我希望能够像这样传递参数: fn(a>=b) or fn(a!=b) 我在 DjangoORM 和 SQLAlchemy 中看到了这种行为,但我不知道如何实现它。 最佳答案 ORM 使用 specia
在我的 Angular 项目中,我最近将 rxjs 升级到版本 6。现在,来自 npm 的模块(在 node_modules 文件夹内)由于一些破坏性更改而失败(旧的进口不再有效)。我为我的代码调整了
这个问题在这里已经有了答案: The issue of * in Command line argument (6 个答案) 关闭 3 年前。 我正在编写一个关于反向波兰表示法的 C 程序,它通过命
$(document).ready(function() { function GetDeals() { alert($(this).attr("id")); } $('.filter
下面是一个例子: 复制代码 代码如下: use strict; #这里是两个数组 my @i =('1','2','3'); my @j =('a','b','c'); &n
我是一名优秀的程序员,十分优秀!