std::string#
std::string (from <string>) manages its own memory: it grows as needed, knows its length and supports +, == and < directly.
Data Science
Length: 12
First char: D, last: e
substr(5, 7): Science
find("Sci"): 5
Computer Science
B.Tech Computer Science
Computer Science| Operation | Example | Result |
|---|---|---|
| length | s.length() or s.size() |
number of characters |
| join | a + b, a += b |
concatenation |
| compare | a == b, a < b |
dictionary order |
| part | s.substr(pos, len) |
sub-string |
| search | s.find("x") |
index or string::npos |
| change | replace, insert, erase |
modify in place |
| convert | to_string(42), stoi("42"), stod("3.5") |
number ↔ text |
apple comes first VEDU-1043, fee/2 = 22999.8 User: asha, domain: vindhya.edu
std::vector - a dynamic array#
A vector<T> (from <vector>) is an array that grows and shrinks by itself and knows its own size. It is the most-used container in C++.
Size: 5 First: 72, last: 57 72 90 65 91 Is empty? false
vector एक ऐसा array है जो ज़रूरत के हिसाब से अपने आप बड़ा-छोटा हो जाता है। push_back से आखिर में element जुड़ता है, size() से गिनती मिलती है और for (int m : marks) से हर element पर आसानी से loop चलता है। C की तरह malloc/free की चिंता नहीं करनी पड़ती।
Reading input into a vector, and sorting#
Sorted: 12 21 33 45 67 89 90 Max: 90 Top 3: 90 89 67
v.begin() and v.end() are iterators - positions that mark the start and one-past-the-end of the data. Most STL algorithms take such a range.
Bounds checking with at()#
v[i] does no checking (like a C array). v.at(i) checks and throws an exception for a bad index:
2 Error: index out of range
Vectors of strings and 2D vectors#
1. Kabir 2. Aditi 3. Rohan 4. Meera 1 2 3 4 2 4 6 8 3 6 9 12
Summary#
std::stringgrows automatically and supports+,==,substr,find,replace,to_string,stoi.std::vector<T>is a resizable array:push_back,pop_back,size,front,back,at.- Use range-for loops (
for (int x : v)) andsort(v.begin(), v.end()). vector<vector<int>>makes a 2D grid.