指针和重复周期 - 我正在尝试节省内存
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);
}
}
我敢打赌,使用带有记录的指针可以节省大量内存,但我无法编译它。我试图理解编译器错误,但对我来说很难 2 ;/
这是编译器的错误列表
> 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
的指针。这两种类型是不兼容的。
第二个问题是pole
if
语句的一个分支不包含 return
语句,从而给你的程序未定义的行为。
您可能希望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
。你也做稍后的地址比较,而不是值指向。这是你想要的吗?
相关文章:
- 将字符串存储在c++中的稳定内存中
- 我应该以字符形式存储数字以节省内存吗?
- C++ 11 通过在类声明中使用指针来节省内存
- 使用常量可以节省内存吗?
- 使用动态库节省内存
- 用于查找范围重叠的更节省内存的算法
- C++:按常用基数对整数进行分组以节省内存
- 通过使用位数组而不是 int 来节省字典的内存
- 如何对上传程序服务器进行速率限制以节省内存
- 使用“std::shared_ptr”时可有效节省内存/编程
- 为什么指针在需要创建指向变量的指针时节省内存
- C++ 块代码在函数完成之前节省内存
- 我是否需要在C++中显式删除数组以节省内存
- 缩小 std::vector 的大小以适应其实际数据以节省内存使用?vec.swap() 在 MSVC 中不起作用?
- 一次只实例化一组类中的一个类,以节省内存
- 静态方法节省内存?(非托管代码)
- 为什么c++仍然不使用vector的共享资源来节省内存
- 指针和重复周期 - 我正在尝试节省内存
- 当许多unordered_map<字符串、双>具有与键完全相同的字符串集时如何节省内存
- Qt 5 dds支持,节省内存和改善渲染