C++代码段可以用于MSVC,但不能用于g++
C++ snippet OK with MSVC but not with g++
我是C++的新手,我试图调整一个程序片段,该片段会生成stackoverflow上的"弱组合"或Multiset,但坦率地说,我运行了好几个小时才出现问题。
首先,该程序在MSVC下运行时没有任何抱怨,但在gcc上没有。
重点是,我在stackoverflow上读过很多类似这样的文章,关于gcc和msvc的不同行为,我已经理解,msvc在处理这种情况时更"自由",而gcc更"严格"。我也理解,不应该"将一个非常数引用绑定到一个临时(内部(变量。">
但我很抱歉,我无法修复它,也无法让这个程序在gcc下工作——从几个小时以来。
如果可能的话,还有第二个问题:我必须引入一个全局变量total
,据说是"邪恶的",尽管它运行良好。我需要这个总值,但是我找不到一个非全局范围的解决方案。
非常感谢大家的帮助。
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int total = 0;
string & ListMultisets(unsigned au4Boxes, unsigned au4Balls, string & strOut = string(), string strBuild = string()) {
unsigned au4;
if (au4Boxes > 1) for (au4 = 0; au4 <= au4Balls; au4++)
{
stringstream ss;
ss << strBuild << (strBuild.size() == 0 ? "" : ",") << au4Balls - au4;
ListMultisets(au4Boxes - 1, au4, strOut, ss.str());
}
else
{
stringstream ss;
ss << mycount << ".t" << "(" << strBuild << (strBuild.size() == 0 ? "" : ",") << au4Balls << ")n";
strOut += ss.str();
total++;
}
return strOut;
}
int main() {
cout << endl << ListMultisets(5,3) << endl;
cout << "Total: " << total << " weak compositions." << endl;
return 0;
}
C++要求对未命名临时(如 这两种引用类型中的任何一种都可以保护您不修改您没有意识到将在当前表达式中销毁的变量。 根据您的需要,它可以将其作为一个值参数: 或者它可以使它成为一个函数局部变量: 在您的示例程序中,任何一个更改都可以。string()
(的引用参数必须是const
引用或r值引用string ListMultisets( ... string strOut = string() ... ) {
string ListMultisets(...) {
string strOut;
删除strOut参数的默认值。
在main中创建一个字符串并将其传递给函数。
将函数的返回类型更改为int。
将total设为局部变量ListMultiset((。返回total而不是strOut(您将返回字符串值strOut作为参考参数。(
新ListMultiset的签名看起来像:
int ListMultisets(unsigned au4Boxes, unsigned au4Balls, string & strOut)
我会让你弄清楚实现的。这要么很简单,要么很有教育意义。
你的新主功能将看起来像:
int main() {
string result;
int total = ListMultisets(5,3, result);
cout << endl << result << endl;
cout << "Total: " << total << " weak compositions." << endl;
return 0;
}
- 是否可以将函数导入命名空间,但不能导出它?
- std::unique_ptr 在 GCC 中工作,但不能在 Visual Studio 中编译
- 声明C++具有动态大小的数组类型在 Linux 中工作正常,但不能在 Windows 中工作
- 为什么我可以隐式地将字符*转换为常量字符*,但不能将无符号字符*
- std::chrono::d uration 可以按秒初始化,但不能按毫秒初始化?
- Python/C++:可以导入犰狳(arma::)但不能导入子程序arma::arma_rng::randn
- 为什么我可以从C++文件中读取 int 值,但不能浮点?
- C++程序在将 int 与 cin 一起使用时有效,但不能使用字符串
- SqLite c++,可以创建数据库,但不能将 anthing 插入到表中
- std::remove() 按预期处理文字,但不能与取消引用的迭代器一起工作
- 16 位系统中的程序如何访问大于 65535 的整数,但不能访问地址
- C++:返回本地对象,但不能正常工作
- 声明适用于 auto,但不能显式声明类型?
- 函数模板可用于本地lambda,但不能用于其他函数
- random_shuffle() 适用于 Windows,但不能在 Linux 上编译
- 自定义分配器可用于vector,但不能用于deque(封装在队列中)
- 用于url编码的c++代码,但不能使用curl
- C++代码段可以用于MSVC,但不能用于g++
- GLSL VertexShader可用于Qt,但不能用于普通OpenGL(SL)
- Map迭代器可用于begin(),但不能用于rbegin()