#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void PrintVector(int v) {
cout << v << endl;
}
void text1() {
vector<int> v;
v.push_back(65);
v.push_back(45);
v.push_back(22);
vector<int>::iterator pBegin = v.begin();
vector<int>::iterator pEnd = v.end();
for_each(pBegin, pEnd, PrintVector);
}
class Person {
public:
Person(int age, int id) :age(age), id(id) {};
int age;
int id;
void Show() {
cout << "the age is " << age << " id is " << id << endl;
}
};
void text2() {
vector<Person> v;
Person p1(10, 20), p2(20, 30), p3(15, 50);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
vector<Person>::iterator pBegin = v.begin();
vector<Person>::iterator pEnd = v.end();
while (pBegin != pEnd) {
(*pBegin).Show();
pBegin++;
}
}
int main() {
text2();
return 0;
}
string容器
string容器特性
- Char* 是一个指针,string是一个类
- String封装了很多实用的成员方法
- 不用考虑内存释放和越界
- string和char*可以通过string类提供的c_str()方法转化
#include<iostream>
#include<vector>
using namespace std;
void test1() {
string s1;
string s2(10, 'a');
string s3("hello");
string s4(s3);
}
void test2() {
string s1;
string s2("hello");
s1 = "world";
cout << s1 << endl;
s1 = s2;
cout << s1 << endl;
s1 = "nihao";
cout << s1 << endl;
s1.assign("hihihi");
cout << s1 << endl;
}
void text3() {
string s1="helloworld";
for (int i = 0; i < s1.size(); i++) {
cout << s1[i] << " ";
}
cout << endl;
for (int i = 0; i < s1.size(); i++) {
cout << s1.at(i) << " ";
}
cout << endl;
try {
cout << s1.at(100) << endl;
}
catch (...) {
cout << "访问越界!" << endl;
}
}
int main() {
text3();
return 0;
}
string操作
#include<iostream>
#include<vector>
using namespace std;
void stringTest() {
string s1 = "hello";
s1 += " world";
cout << s1 << endl;
string s2 = "hihihi";
string s3 = " nihao";
s2.append(s3);
cout << s2 << endl;
}
void stringTest2() {
string s1 = "hello";
int pos = s1.find('l');
int pos2 = s1.rfind('l');
cout << "从前往后:" << pos << endl;
cout << "从后往前:" << pos2 << endl;
s1.replace(0, 2, "8888");
cout << s1 << endl;
}
void stringTest3() {
string s1 = "abcd";
string s2 = "sccd";
if (s1.compare(s2) == 0) {
cout << "两个字符串相等" << endl;
}
else {
cout << "字符串不相等" << endl;
}
}
void stringTest4() {
string s = "abcdefg";
string s2 = s.substr(1, 3);
cout << s2 << endl;
}
void stringTest5() {
string s = "HELLOWORLD";
s.insert(5, " *** ");
cout << s << endl;
s.erase(5, 5);
cout << s << endl;
}
int main() {
stringTest5();
return 0;
}