【发布时间】:2018-12-04 00:27:48
【问题描述】:
我正在尝试在 cpp 中从数组转移到向量,以解决问题及其整体优势。即使此逻辑适用于数组,我在这里也面临一些问题。
#include <iostream>
#include <vector>
using namespace std;
void PrintArray(vector<int> v) { // O(n)
for (int i=0; i<v.size(); i++)
cout << v[i] << " ";
cout << endl;
}
void LF1(vector<int> A) { // O(n)
int temp = A[0],i;
for (i=0; i<A.size()-1; i++)
A.at(i) = A.at(i+1);
A.at(i)=temp;
// PrintArray(A); <-- shows updated array here
}
void LF(vector<int> A, int d) {
d = d % (A.size());
cout << "d%n: " << d << endl;
for (int j=0; j<d; j++)
LF1(A);
PrintArray(A);
}
int main(int argc, char const *argv[]) {
vector<int> A;
int d;
for(int i=1; i<6; i++)
A.push_back(i);
PrintArray(A);
cout << "Enter number of Left rotations to perform : ";
cin >> d;
LF(A,d);
return 0;
}
问题 1: 当我在 LF 内部调用 LF1 时,它返回相同的数组而不旋转,但是当我在 LF 内部编写 LF1 的代码时,它似乎在旋转。
问题 2: PrintArray() 仅在从 LF1() 调用时或在其代码之后立即在 LF() 中写入(而不是调用 LF1())时打印旋转数组它打印数组 d 次。其中 d 是所需的旋转次数。
【问题讨论】:
-
您正在按值传递参数。该函数对参数的副本进行操作;论点保持不变。您的功能是精心设计的无操作。在您最喜欢的 C++ 教科书中阅读有关通过引用传递的内容。
-
欢迎来到 StackOverflow。你的问题还不错(我不这么认为)......而且考虑到 C 的 unusual array-decaying-behavior,这是一个合理的混淆。但这仍然是一个相当 基本 的问题......所以投票者可能认为阅读基础书籍比在 StackOverflow 上反复试验更好。这是有道理的,所以不要害怕阅读一本书,there are some good ones。