Skip to content

Latest commit

 

History

History
90 lines (89 loc) · 1.48 KB

modern_cpp.md

File metadata and controls

90 lines (89 loc) · 1.48 KB

Modern C++ (C++11 & beyond)

Old vs New

  • Variable Initialization
    • int a = 1;
    • int a{1};
    • print using std::cout << a << std::endl;
  • String Initialization
    • string s = "abhijit";
    • string s{"abhijit"};
    • print using std::cout << s << std::endl;
  • Vector Initialization
    • 1
vector <int> v;
v.push_back(10);
v.push_back(20);
- 2
vector <int> v{10,20};
- print using
//print
std::cout << v.at(0) << std::endl;		// print 0th i.e. 1st element
std::cout << v.at(1) << std::endl;		// print 1st i.e. 2nd element
std::cout << v.at(2) << std::endl;		// Gives Error: 'std::out_of_range'
  • Map initialization
    • 1
map<string, string> capitals = {
	{"UK", "london"}, {"India", "Delhi"}
};
- 2
map<string, string> capitals {
	{"UK", "london"}, {"India", "Delhi"}
};
- print using
for(auto&& i : capitals) {
	std::cout << i.first << ": " << i.second << std::endl;	
}
  • Struct Initialization
    • define struct
struct Person
{
	string name;
	int age;
};
- 1
Person p = {"abhijit", 27};
- 2
Person p{"abhijit", 27};
- print using
std::cout << p.name << ", " << p.age << std::endl;
  • Namespace Initialization
    • 1
namespace A {
	namespace B {
		namespace C {
			void bar(){};
		}
	}
}
- 2
namespace A::B::C {
	void bar(){};
}
- calling in main function
A::B::C::bar();