在 C++ 中,如果函数返回 a std::pair<int, int>,我们可以按如下方式自动接收它:
auto pr = some_function();
std::cout << pr.first << ' ' << pr.second;
Run Code Online (Sandbox Code Playgroud)
现在,C++17 标准提供了一种将这对直接解包为单独变量的漂亮方法,如下所示:
auto [x, y] = some_function();
std::cout << x << ' ' << y;
Run Code Online (Sandbox Code Playgroud)
然后是std::minmax_element()库函数,它返回一对迭代器。所以如果我将 a 传递vector<int>给这个函数,它会给我一对指向向量中最小和最大元素的迭代器。
现在我可以像往常一样接受这些迭代器的一种方法,然后按如下方式取消引用它们。
std::vector<int> v = {4,1,3,2,5};
auto [x, y] = std::minmax_element(v.begin(), v.end());
std::cout << (*x) << ' ' << (*y); // notice the asterisk(*)
Run Code Online (Sandbox Code Playgroud)
现在我的问题是:有没有办法在解包时取消引用它们?或者更准确地说,给定以下代码,我可以用有效的 C++替换var1和var2并打印这些迭代器指向的值吗?
std::vector<int> v = {4,1,3,2,5};
auto [var1, …Run Code Online (Sandbox Code Playgroud) 在 python 中,我们有一个名为nonlocal. 它和staticC++中的一样吗?如果我们在python中有嵌套函数,而不是在内部函数内部使用nonlocal,我们不能在外部函数中声明变量吗?这样就真的了nonlocal。
说明:staticC++ 中使用的关键字如下:
#include <iostream>
int foo () {
static int sVar = 5;
sVar++;
return sVar;
}
using namespace std;
int main () {
int iter = 0;
do {
cout << "Svar :" foo() << endl;
iter++;
} while (iter < 3);
}
Run Code Online (Sandbox Code Playgroud)
给出迭代输出:
Svar :6
Svar :7
Svar :8
Run Code Online (Sandbox Code Playgroud)
因此,Svar 正在保留其价值。
在C ++中,如果我这样做:
std::vector words {"some","test","cases","here"};
Run Code Online (Sandbox Code Playgroud)
谁能解释为什么words不是一种std::vector<std::string>容器?
C ++是否应该通过我提供的初始化列表来推断类型?
如果“ some”,“ test”不是字符串文字,那么std :: string文字看起来像什么?
以下简单代码(二进制文件处理)在与 Windows 的 Codeblocks 17.12 (mingw32-g++) 捆绑的编译器上运行良好,但在 Linux(在 Ubuntu 19.10 上)使用 g++ 9.2.1 时出现分段错误:
#include <iostream>
#include <fstream>
using namespace std;
class A {
public:
int x;
string y;
};
int main()
{
ofstream k;
A m;
m.x = 10;
m.y = "Hello";
k.open("file.dat", ios::binary);
k.write(reinterpret_cast<char *>(&m), sizeof(A));
k.close();
ifstream i;
A t;
i.open("file.dat", ios::binary);
i.seekg(0, ios::beg);
i.read(reinterpret_cast<char *>(&t), sizeof(A));
cout << t.x << " " << t.y;
i.close();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我做错了什么,windows 上的最小 g++ 原谅了我,但 g++-Linux 不是?还是我发现了一个错误?