使用引用交换两个变量
#include <iostream>
using namespace std;
void swap2(int &a, int &b) {
int t = a;
a = b;
b = t;
}
int main() {
int a = 3, b = 4;
swap2(a, b);
cout << a << " " << b << "\n";
return 0;
}
string
输入数据的每行包含若干个(至少一个)以空格隔开的整数,输出每行中所有整数的和。
#include <iostream>
#include <string> // 慢
#include <sstream> // 更慢
using namespace std;
int main() {
string line;
while (getline(cin, line)) {
int sum = 0, x;
stringstream ss(line);
while (ss >> x)
sum += x;
cout << sum << "\n";
}
return 0;
}
结构体
#include <iostream>
using namespace std;
struct Point
{
int x, y;
Point(int x = 0, int y = 0) : x(x), y(y){ // 构造函数
}
};
Point operator + (const Point& A, const Point& B)
{
return Point(A.x + B.x, A.y + B.y);
}
ostream& operator << (ostream& out, const Point& p)
{
out << "(" << p.x << "," << p.y << ")";
return out;
}
int main()
{
Point a, b(1, 2);
a.x = 3;
cout << a + b << "\n";
return 0;
}
使用swap时建议将深浅复制加进去(不成熟的建议
hh,我对C++的学习还不太深入,竞赛够用就行。