C++

[C++] Convert between string and int

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

int main()
{ 
 stringstream ss;
 string s="456";
 int x;
 
 //string to int(or double etc...)
 ss<<s;
 ss>>x;
 cout<<x;

 //string to int using stoi 
 x = stoi(s);
 //clean up stringstream
 
 ss.str("");
 ss.clear();
 
 //int(or double etc...) to string
 x=100;
 s=to_string(x);
 cout<<s;
 
 return 0;
}

[C++] String Processing

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

int main()
{ 
 string s="ab@c";
 
 //reverse and begin() end()
 reverse(s.begin(),s.end());
 cout<<s<<endl;

 //
 cout<<s.length()<<endl;
 cout<<s.empty()<<endl;
 
 //s.swap(b) swap content with string b
 cout<<(int)s.find('@')<<endl;
 cout<<(int)s.find('9')<<endl;
 
 //substr 
 cout<<s.substr(1,2)<<endl;
 cout<<s.substr(0)<<endl;
 
 //erase(delete nth element)
 cout<<s.erase(s.begin()+n);
 return 0;
}

[C++] Tip for Reference

References have to be initialized, and will represent the variables assigned to them.

int x=10,y=5;

//wrong
int &A;
A=x;

//right
int &A=x;

//set x's value by y
A=y;

[C++] typeid()

#include<iostream>
#include<typeinfo>
using namespace std;

int main()
{
    int x;
    cout << typeid(x).name() << endl;
    system("pause");
    return 0;
}

[C++] *x++、*++x、*x+1

*x++ same as *(x++)

*++x same as *(++x)

*x+1 same as (*x)+1

[C++] swap(T &a, T &b)

//#include<algorithm> to use this template

template <class T> void swap (T& a, T& b)
{
    T c(std::move(a)); a=std::move(b); b=std::move(c);
}
template <class T, size_t N> void swap (T (&a)[N], T (&b)[N])
{
    for (size_t i = 0; i<N; ++i) swap (a[i],b[i]);
}