

int* ptr = nullptr;
try//检测是否存在抛异常
{
ptr = new int[n] {初始化值(如果是一个值初始化时用“()”)};//n为对象的个数
}
catch(const std::exception& e)//检测是否存在抛异常
{
std::cout << e.what() << std::endl;
}
delete[] ptr;#include<iostream>
#include<string>
int main()
{
char ch[10] = "abcdefg";
string s1(ch);
for(int i = 0;i < s1.size();++i)
{
std::cout << s1[i] << std::endl;
}
return 0;
}//迭代器的英文为iterator,故用它来定义迭代器变量。
//begin()和end()都是返回容器开头和结尾的迭代器函数。
string::iterator (变量名) = (类对象名).begin();
使用示例:
用迭代器打印string中的字符
#include<string>
int main()
{
std::string s1("abcdefg");
std::string::iterator it = s1.begin();
while(it != s1.end())
{
std::cout << it << " ";
++it;
}
return 0;
}string s1;
s1.push_back('a');std::string s1;
s1 += "abcdefg";
s1 += 'a';std::string s1("abcdefg");
//提取s1中的所有字符
std::string s2 = s1.substr(0);
//提取s1中下标为1长度为3的字符串。
std::string s3 = s1.substr(1,3);std::string s1("abcdefg");
//从下标为零的的位置开始查找字符或字符串
size_t pos = s1.find('c');
//从下标为一的的位置开始查找字符或字符串
size_t pos = s1.find('c',1);std::string s1("abcdefghjijk");
//打印string中的字符串
std::cout << s1.c_str() << std::endl;