Skip to content

Instantly share code, notes, and snippets.

@songron
Last active December 28, 2015 20:19
Show Gist options
  • Save songron/7556645 to your computer and use it in GitHub Desktop.
Save songron/7556645 to your computer and use it in GitHub Desktop.
复习C++的代码。都是很简单很基础的代码,目的是复习C++的语法规则和编码风格,也便于以后的回顾。主要参考是:C++ Language Tutorial (http://www.cplusplus.com/doc/tutorial/)
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
using namespace std;
void funa(int [][3], int);
int main()
{
int arr [5] = {1,5,10,6,9};
int arr2 [] = {1,2,3};
arr[2] = 100;
for (int i=0; i<5; i++) {
cout << arr[i] << endl;
}
int arr3[2][3];
for (int i=0; i<2; i++) {
for (int j=0; j<3; j++){
arr3[i][j] = i * j;
}
}
funa(arr3, 2);
for (int i=0; i<2; i++) {
for (int j=0; j<3; j++){
cout << arr3[i][j] << ' ';
}
cout << endl;
}
char carr [] = {'h', 'e', 'l', 'l', 'o'};
char carr2 [] = "hello";
cout << carr << '\t' << carr2 << endl;
return 0;
}
void funa(int arr[][3], int n)
{
for (int i=0; i<n; i++)
for (int j=0; j<3; j++)
arr[i][j] = 10 * j;
}
复习C++的代码。都是很简单很基础的代码,目的是复习C++的语法规则和编码风格,也便于以后的回顾。
主要参考是:C++ Language Tutorial (http://www.cplusplus.com/doc/tutorial/)
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
using namespace std;
/*
* private members of a class are accessible only from within other members of the same class or from
* their friends.
* • protected members are accessible from members of their same class and from their friends, but also
* from members of their derived classes.
* • Finally, public members are accessible from anywhere where the object is visible.*
* By default, members have private access.
*/
class Shape {
int x, y;
public:
static int counter; // static variable == class variable
Shape(int, int); // the constructor
Shape(); // another constructor
~Shape();
void set_values(int, int);
int area() { return x*y; }
};
int Shape::counter = 0;
Shape::Shape ()
{
counter++;
x = 50;
y = 55;
}
// "this" is a pointer to the object itself
Shape::Shape (int x, int y)
{
counter++;
this->x = x;
this->y = y;
}
Shape::~Shape ()
{
counter--;
cout << "I'm dead.\n";
}
void Shape::set_values(int x, int y)
{
this->x = x;
this->y = y;
}
class Test {
int x, y;
public:
Test(int, int);
void show() { cout << x << ' ' << y << endl; }
};
Test::Test(int x, int y) : x(x), y(y)
{
}
int main()
{
// Shape sh (10, 20);
Shape sh; // wrong: Shape sh();
int a = sh.area();
cout << a << endl;
cout << "Counter: " << Shape::counter << endl;
Shape * psh = new Shape (10, 20);
cout << psh->area() << endl;
cout << "Counter: " << Shape::counter << endl;
delete psh;
cout << "Counter: " << Shape::counter << endl;
Shape sh2 = sh; // it's copy, not reference; here the constructor not executed
sh2.set_values(100, 500);
cout << sh.area() << ' ' << sh2.area() << endl;
cout << "Counter: " << Shape::counter << endl;
cout << endl;
Test t(1000, 40000);
t.show();
return 0;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
using namespace std;
class Square;
class Shape {
int x, y;
public:
Shape(int, int);
int area() {return (x * y);}
friend void show (Shape); // declare a friend function "show"
void convert(Square); // it's valid because "Shape" is a friend of "Square"; but not the reverse way
};
class Square {
int side;
public:
Square(int);
int area() {return (side * side);}
friend class Shape; // a friend class
};
Shape::Shape(int x, int y)
{
this->x = x;
this->y = y;
}
void Shape::convert(Square sq)
{
this->x = sq.side;
this->y = sq.side;
}
void show(Shape sh)
{
cout << "Length: " << sh.x << endl;
cout << "Width: " << sh.y << endl;
}
Square::Square(int side)
{
this->side = side;
}
int main()
{
Shape sh(15, 20);
cout << "Area: " << sh.area() << endl;
show(sh);
Square sq(11);
sh.convert(sq);
cout << "Area: " << sh.area() << endl;
return 0;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
using namespace std;
// the constructor, destructor and friends are not inherited
class Polygon {
protected:
int w, h;
public:
Polygon() { cout << "I'm in Polygon's constructor.\n"; };
Polygon(int, int);
};
// the keywork "public" control the accessable of the variables in Rectangle inherited from Polygon
class Rectangle: public Polygon {
public:
Rectangle(int, int);
int area() { return (w*h); }
};
class Triangle: public Polygon {
public:
float area() { return (w*h/2.0); }
};
Polygon::Polygon(int w, int h)
{
this->w = w;
this->h = h;
cout << "I'in the second constructor.\n";
}
Rectangle::Rectangle(int w, int h) : Polygon(w, h)
{
// this->w = w;
// this->h = h;
}
int main()
{
Rectangle rect(10, 20);
cout << rect.area() << endl;
return 0;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
#include <string>
using namespace std;
class Show {
public:
void show(int);
};
void Show::show(int x)
{
cout << x << endl;
}
class Father {
int x;
public:
Father(int x) {this->x=x;}
int get_value() { return x; }
};
class Son: public Father, public Show {
public:
Son(int x) : Father(x) {}
};
int main()
{
Son s(1000);
s.show(s.get_value());
return 0;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
using namespace std;
/*
class Polygon {
protected:
int x, y;
public:
void set_values (int x, int y) {this->x = x; this->y = y;}
// virtual member: for redefined in the derived classes
virtual float area() { return 0; }
};
*/
// this is an Abstract Class
class Polygon {
protected:
int x, y;
public:
void set_values (int x, int y) {this->x = x; this->y = y;}
// pure virtual function ! Must be "=0"
virtual float area() = 0;
};
class Rectangle : public Polygon {
public:
float area () { return (x*y); }
};
class Triangle : public Polygon {
public:
float area () { return (x*y/2.0); }
};
int main()
{
Rectangle rect;
Triangle tri;
Polygon *p1 = &rect;
Polygon *p2 = &tri;
Polygon *p3 = new Triangle;
p1->set_values(10,20);
p2->set_values(10,20);
p3->set_values(5,5);
cout << p1->area() << endl;
cout << p2->area() << endl;
cout << p3->area() << endl;
return 0;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
using namespace std;
int main()
{
int a = 100;
bool b = false;
if (b)
cout << "yes\n";
else
cout << "no\n";
if (a <= 99)
cout << "a is smaller than 100\n";
else if (a == 100)
cout << "a is 100\n";
else
cout << "a is arger than 100\n";
int n = 10;
while (n) {
cout << n << endl;
if (n == 5)
break;
n--;
}
int i = 0;
do {
cout << i << endl;
i--;
} while (i > 0);
for (int i=0; i<5; i++) {
if (i == 3)
continue;
cout << i << ' ';
}
cout << endl;
cout << i << endl;
i = 2;
// i should be an integer variable; and case value should be an integer constant !
switch (i) {
case 1:
cout << "one\n";
break;
case 2:
cout << "tow\n";
break;
case 3:
cout << "three\n";
break;
default:
cout << "No match !\n";
}
return 0;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
// about data types in C++
#include <iostream>
#include <string>
using namespace std;
// -- defined constants --
#define PI 3.1415926
int main()
{
char c; // 1 byte
int n; // 4 bytes
bool b = true;; // true or false
float f; // 4 bytes
double d; // 8 bytes
const int cn = 100;
b = false;
cout << b << '\n';
string s = "this is a string line\n";
string s2 ("this is the second string line \n");
cout << s << s2;
s = "A new string";
cout << s << endl;
cout << PI << endl;
// conditional operator;
n = 1 ? cn > 100 : 0;
cout << n << endl;
// comma: assign the rightmost value
n = (1,2,3,4,5);
cout << n << endl;
// type casting
f = 1.55678;
n = (int) f; // or n = int(f);
// n = int(f);
cout << n << endl;
n = sizeof(f);
cout << n << endl;
return c;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
#include <exception>
using namespace std;
class myexception: public exception
{
virtual const char* what() const throw()
// virtual const char* what() throw()
{
return "My exception!!";
}
};
int main()
{
myexception mye;
try {
// throw 20.5;
throw mye;
}
catch (int e) {
cout << "Exception: " << e << endl;
}
catch (exception& e) {
cout << "Exception: " << e.what() << endl;
}
catch (...) {
cout << "Exception\n";
}
return 0;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
using namespace std;
int addition(int, int);
void sayhello(void);
void argu_value(int);
void argu_refer(int&);
int fab(int);
int main()
{
int r;
r = addition(1, 2);
cout << r << endl;
sayhello();
// arguments passed by value or by reference
argu_value(r);
cout << r << endl;
argu_refer(r);
cout << r << endl;
int n;
cin >> n;
cout << fab(n) << endl;
return 0;
}
int addition (int a, int b)
{
return (a + b);
}
void sayhello (void)
{
cout << "Hello world !\n";
}
void argu_value(int n)
{
n *= 2;
}
void argu_refer(int& n)
{
n *= 2;
}
// Recursivity
int fab(int n)
{
if (n == 0)
return 0;
if (n == 1)
return 1;
return (fab(n-1) + fab(n-2));
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
// my first test program in c++
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world !\n";
cout << "Hello C++ !\n";
return 0;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
int x = 250;
string s = "Hello world! My name is ";
cout << "你好" << endl;
cout << x << endl;
cout << s << "Rong" << endl;
// cin >> x >> s;
// cout << x << '\t' << s << endl;
// getline (cin, s);
s = "1234ab";
stringstream(s) >> x; // x will be 1234
cout << x << endl;
return 0;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
using namespace std;
namespace nsp1
{
int var = 1000;
}
namespace nsp2
{
float var = 10.57;
}
int main()
{
cout << nsp1::var << endl;
cout << nsp2::var << endl;
{
using namespace nsp1;
cout << var << endl;
}
{
using namespace nsp2;
cout << var << endl;
}
using nsp2::var;
cout << var << endl;
return 0;
}
注意:
关于 cin, getline, string
getline 用 string 接收一行:
string line;
getline(cin, line);
直接用cin 读取参数后,再使用getline 时,getline 读取的依然是当前行的数据。
如数据:
12 13
10
代码:
int a, b;
cin >> a >> b;
getline(cin, line);
// 此时line 会是一个空串,而不是下一行的"10"
geline 会忽略最后的换行符"\n",但会保留其他空白符。
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream of;
of.open("outfile.txt", ios::out | ios::app);
of << "My test output file.\n";
of.close();
string line;
ifstream f;
f.open("outfile.txt");
while (! f.eof()) {
getline (f, line);
cout << line << endl;
}
f.close();
return 0;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
using namespace std;
int main()
{
int x = 10;
// the address is called reference, exp: &a
// the variable that stores the reference is called pointer
int* p = &x;
cout << p << '\t' << *p << '\t' << x << endl;
*p = 199;
cout << p << '\t' << *p << '\t' << x << endl;
int nums[5];
p = nums;
for (int i=0; i<5; i++){
*p = 100 * i;
p++;
}
for (int i=0; i<5; i++)
cout << nums[i] << ' ';
cout << endl;
// char carr[] = {'h', 'i'};
// char * cp = carr;
char * cp = (char *)("how are you");
cout << cp << endl;
// next: Pointer arithmetics
return 0;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
using namespace std;
int main()
{
cout << "The file is: " << __FILE__ << endl;
cout << "This line number: " << __LINE__ << endl;
cout << "Compiled at: " << __TIME__ << endl;
return 0;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
#include <map>
#include <string>
using namespace std;
/* map powered by binary search tree */
int main()
{
map<string, string> mymap;
map<string, string>::iterator it;
mymap["name"] = "rongxiaosong";
mymap["age"] = "24";
mymap["school"] = "puk";
it = mymap.end();
mymap.insert(it, pair<string, string>("home", "jixian"));
mymap.insert(it, pair<string, string>("home", "jixian")); // replace
pair<string, string> mypair ("hobby", "guitar");
mymap.insert(mypair);
for (it=mymap.begin(); it!=mymap.end(); ++it) {
cout << it->first << ": " << it->second << endl;
}
cout << endl;
cout << mymap["school"] << endl;
it = mymap.find("age");
cout << it->first << ": " << it->second << endl;
it = mymap.find("xxxx");
if (it == mymap.end())
cout << "\"xxx\" not found\n";
return 0;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
int nums[] = {10, 9, 7, 1, 3};
sort(nums, nums+5);
for (int i=0; i<5; i++) {
cout << nums[i] << ' ';
}
cout << endl;
cout << *min_element(nums, nums+5) << '\t' << *max_element(nums, nums+5) << endl;
cout << max_element(nums, nums+5) << endl;
cout << max_element(nums+5, nums+5) << endl; // empty range, return the "last" pointer
return 0;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
/* Not supported by older compilers */
/* unordered_map powered by hash function */
int main()
{
unordered_map<string, string> mymap;
mymap["name"] = "rongxiaosong";
mymap["age"] = "24";
mymap["school"] = "puk";
for(unordered_map::iterator it=mymap.begin(); it!=mymap.end(); ++it) {
cout << it->first << ": " << it->second << endl;
}
return 0;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec;
int n;
while (cin >> n) {
vec.push_back(n);
}
cout << int(vec.size()) << endl;
cout << vec.back() << endl;
return 0;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
using namespace std;
struct product {
int weight;
float price;
};
void foo(product&);
int main()
{
product prod;
prod.weight = 100;
prod.price = 1.5;
cout << prod.weight * prod.price << endl;
foo(prod);
cout << prod.weight * prod.price << endl;
product *p = &prod;
// p->weight == (*p).weight != *p.weight == *(p.weight)
cout << p->weight << ' ' << p->price << endl;
return 0;
}
void foo(product& prod)
{
prod.weight = 90;
}
// Copyright (c) 2013 Peking University.
// Author: Xiaosong Rong (rongxiaosong@gmail.com)
#include <iostream>
using namespace std;
// function Template
template <class T>
T getMax(T a, T b)
{
return (a > b ? a : b);
}
// function Template with two classes
template <class T, class U>
void print(T a, U b)
{
cout << a << ' ' << b << endl;
}
// class Template
template <class T>
class Mypair {
T x, y;
public:
Mypair (T x, T y)
{this->x = x; this->y = y;}
void print_max();
};
template <class T>
void Mypair<T>::print_max()
{
T r;
r = x > y? x : y;
cout << r << endl;
}
// Template specialization
template <class T>
class Container {
T e;
public:
Container (T e) { this->e = e; }
T increase () { return ++e; }
};
template <>
class Container<char> {
char e;
public:
Container (char e) { this->e = e; }
void show_upper ()
{
if (e>='a' && e<='z')
e = e + 'A' - 'a';
cout << e << endl;
}
};
// Non-type parameters & default values for params
template <class T=int, int N=10>
class Sequence {
T seq [N];
public:
void set_value (int, T);
T get_value (int);
};
template <class T, int N>
void Sequence<T, N>::set_value (int i, T v)
{
seq[i] = v;
}
template <class T, int N>
T Sequence<T, N>::get_value (int i)
{
return seq[i];
}
int main()
{
cout << getMax<int>(10, 15) << endl;
cout << getMax<float>(10.9, 15.3) << endl;
cout << getMax<>(0.9, 0.5) << endl;
cout << getMax(10, 39) << endl;
print<int, float>(1, 10.4);
print(1.5, 10);
cout << endl;
Mypair<int> mp (100,150);
mp.print_max();
Container<int> c1 (100);
Container<char> c2 ('b');
cout << c1.increase() << endl;
c2.show_upper();
// Sequence<int, 10> se;
Sequence<> se;
se.set_value(5, 1034);
cout << se.get_value(5) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment