![](/img/trans.png)
[英]I'm trying to read in class pointers to a vector with a for loop, but it only works if I declare object inside loop
[英]Pointers and recurency - I'm trying to save memory
我正在嘗試編寫為字符串創建squere的程序。 Squere必須大於string.length()。 如果有'C ++'字樣,我需要2x2數組來填充它。 所以我寫了代碼
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int pole(int &a,const int* l);
int main(){
string code;
cin >> code;
int wall=1;
pole(wall,code.length());
cout << wall;
system("PAUSE");
return 0;
}
int pole(int &a,const int* l){
if (a*a > l) return a;
else {
a+=1;
pole(a,l);
}
}
我敢打賭,使用具有recunrency的指針可以節省大量內存,但我無法編譯它。 我正在努力理解編譯器錯誤,但對我來說很難; /
這是編譯器錯誤列表
> in main()
11 25 Error] invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int (*)(int&, const int*)'
6 5> [Error] in passing argument 1 of 'int pole(int&, const int*)'
in pole() 17 12
>[Error] ISO C++ forbids comparison between pointer and
> integer [-fpermissive]
這里:
pole(pole, code.length());
您將第二個變量作為length()
的結果傳遞,它的類型為std::string::size_type
,函數pole
接受指向int
的指針。 這兩種類型是不兼容的。
第二個問題是你的if
語句在pole
內的一個分支不包含return
語句,因此給你的程序Undefined Behavior。
您可能希望以這種方式更改功能pole
:
int pole(int &a, std::string::size_type l) {
// ^^^^^^^^^^^^^^^^^^^^^^
// Also, passing by reference is unnecessary here
if (a*a > static_cast<int>(l)) return a;
// ^^^^^^^^^^^^^^^^
// Just to communicate that you are aware of the
// signed-to-unsigned comparison here
else {
a+=1;
return pole(a,l);
// ^^^^^^
// Do not forget this, or your program will have Undefined Behavior!
}
}
在這里,您可以看到您修改的程序編譯和運行。
您正在嘗試使用無符號整數 (來自std::string::length
)作為指針:
pole(wall,code.length());
將您的極點聲明更改為:
int pole(int a, int l);
在int
上保存內存只是廢話。 指針有時甚至比簡單整數更昂貴。
您應該學會用大型對象來節省內存。
int pole(int &a,const int* l){
if (a*a > l) return a;
else {
a+=1;
pole(a,l);
}
}
首先,您不能使用size_t
參數初始化int* l
。 你也可以在以后比較地址,而不是指向值。 這是你想要的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.