1. 程式人生 > 實用技巧 >STL基礎部分

STL基礎部分

string

輸入輸出字串

#include <bits/stdc++.h>
using namespace std;

int main(){
//    string s = "12312hello world...";
    string s;
    getline(cin, s);//輸入字串
    cout<<s;
    return 0;
}
21314 hello woefsdcsd
21314 hello woefsdcsd
Process finished with exit code 0

字串拼湊

#include <bits/stdc++.h>
using namespace std;

int main(){
//    string s = "12312hello world...";
    string s;
    s += "shda s";
    s += "shda s";
    s += '5';

    cout<<s;
    return 0;
}
shda sshda s5
Process finished with exit code 0

排序

#include <bits/stdc++.h>

using namespace std;

int main() {
    string s = "1523525431873";
    sort(s.begin(), s.end());
    cout << s;
    return 0;
}
1122333455578
Process finished with exit code 0
  • s.begin(), s.end()是迭代器,可以看成是指標
  • 如果要訪問最後一個字元,應該是*(--s.end())

erase刪除

#include <bits/stdc++.h>

using namespace std;

int main() {
    string s = "1523525431873";
    s.erase(s.begin());
    s.erase(--s.end());
    cout << s;
    return 0;
}
52352543187
Process finished with exit code 0

substr取子串

#include <bits/stdc++.h>

using namespace std;

int main() {
    string s = "1523525431873";
    s = s.substr(2, 3);//從索引為2開始取,往後取三個
    cout << s;
    s = "1523525431873";
    s = s.substr(6, -1);//從索引為6開始取,直到最後一個
    cout << endl << s;
    return 0;
}
235
5431873
Process finished with exit code 0

幾種迴圈方式

#include <bits/stdc++.h>

using namespace std;

int main() {
    string s = "1523525431873";
    for (int i = 0; i < s.length(); ++i)
        cout << s[i];

    cout << '\n';
    for (string::iterator iter = s.begin(); iter != s.end(); iter++)
        cout << *iter;
    
    cout << '\n';
    for (auto i : s)
        cout << i;


    cout << endl << s;
    return 0;
}
1523525431873
1523525431873
1523525431873
1523525431873
Process finished with exit code 0

vector