First, the transition mentioned here refers to applications in algorithm competitions, so please do not get it wrong.Welcome to join the QQ group: 784980490. In algorithm competitions, the main differences between C and C++ are as follows:
STL Containers – The Ultimate Tool for Competitions
In C++, many containers are pre-written, which simplifies programming and saves some unimportant work.For example:
// vector - dynamic array
vector<int> v = {1, 2, 3};
v.push_back(4); // insert at the end
v.pop_back(); // remove from the end
sort(v.begin(), v.end()); // sort
// queue - queue
queue<int> q;
q.push(1);
q.pop();
// stack - stack
stack<int> s;
s.push(1);
s.pop();
// set - ordered set
set<int> st;
st.insert(3);
st.erase(2);
if (st.find(3) != st.end()) {} // find
// map - key-value pair
map<string, int> mp;
mp["hello"] = 1;
mp.count("hello"); // find key
Algorithm Header Files – The Cheat Tool
The richness of header files greatly simplifies some calculations, such as sorting, where a single sort is enough, and binary search, etc.
vector<int> v = {3, 1, 4, 1, 5};
// sort
sort(v.begin(), v.end()); // default ascending
sort(v.begin(), v.end(), greater<int>()); // descending
// find
auto it = find(v.begin(), v.end(), 4);
if (it != v.end()) {} // found
// binary search
bool exists = binary_search(v.begin(), v.end(), 3);
// reverse
reverse(v.begin(), v.end());
// max and min values
int max_val = *max_element(v.begin(), v.end());
int min_val = *min_element(v.begin(), v.end());
String Handling
In C++, strings are introduced, which are commonly referred to as character arrays in C.
#include <string>
string str = "hello";
str += " world"; // string concatenation
// common operations
str.length(); // length
str.substr(0, 5); // substring
str.find("world"); // find
stoi(str); // string to integer
to_string(123); // number to string
So how should one proceed?First, the most common is to speed up input and output.
// C language
scanf();
printf();
// C++
cin cout
And the STL containers (must master, very convenient):
vector<int> v; // dynamic array - most commonly used
queue<int> q; // queue - essential for BFS
stack<int> st; // stack
string s; // string - much more convenient than char[]
pair<int,int> p; // pair
Some algorithm functions:
sort(v.begin(), v.end()); // sort
reverse(v.begin(), v.end()); // reverse
max_element(v.begin(), v.end()); // maximum
binary_search(v.begin(), v.end(), target); // binary search
Finally, there’s the universal header (commonly used in algorithm competitions)
#include <bits/stdc++.h>
As for other conventions, they are generally consistent.