您的位置:首页 > 编程语言 > C语言/C++

C++primer5th课后题12.6、12.14、12.19

2016-11-14 17:03 141 查看
//习题12.6
//返回动态分配的int的vector,传递给另一个函数,读取标准输入保存为vector元素中,
/*shared_ptr<vector<int>> new_factor(void)
{
return make_shared<vector<int>>();
}
vector<int> *new_vector(void)
{
return new (nothrow) vector<int>;
}
void read_ints(vector<int> *pv)
{
int v;
while (cin >> v)
//pv->push_back(v);
(*pv).push_back(v);
}
void print_ints(vector<int> *pv)
{
for (const auto &v : *pv)
cout << v << " ";
cout << endl;
}

int main()
{
vector<int> *pv = new_vector();
if (!pv) {
cout << "内存不足" << endl;
return -1;
}
read_ints(pv);
print_ints(pv);
//delete pv;
//pv = nullptr;
return 0;
}*/
//习题12.14
/*
struct destination{};
struct connection{};
connection connect(destination *pd)
{
cout << "打开连接" << endl;
return connection();
}
void disconnect(connection c)
{
cout << "关闭连接" << endl;
}
void f(destination &d)
{
cout << "直接管理connect" << endl;
connection c = connect(&d);
//未关闭连接
cout << endl;
}
void end_connection(connection *p) { disconnect(*p); }
void f1(destination &d)
{
cout << "用shared_ptr管理connection" << endl;
connection c = connect(&d);
//shared_ptr<connection> p(&c, [](connection *p) { disconnect(*p); });// end_connection);
unique_ptr<connection, decltype(end_connection) *> p(&c, end_connection);
cout << endl;

}
int main()
{
destination d;

f(d);
f1(d);
//return 0;
}*/
//习题12.19
//-----------------------------------------------
int main()
{
StrBlob b1;
{
StrBlob b2 = { "
9e6c
a","an","the" };
b1 = b2;
b2.push_back("about");
cout << b2.size() << endl;
}
cout << b1.size() << endl;
cout << b1.front() << " " << b1.back() << endl;

const StrBlob b3 = b1;
cout << b3.front() << " " << b3.back() << endl;

for (auto it = b1.begin(); neq(it, b1.end()); it.incr())//b1.begin()返回StrBlobPtr
cout << it.deref() << endl;
return 0;
}
int main()
{
StrBlob b;
ifstream in("1.txt");
if (!in) {
cerr << "打开失败!";
return -1;
}
string line, word;
while (getline(in, line))
b.push_back(line);
for (auto it = b.begin(); neq(it, b.end()); it.incr())
cout << it.deref() << 'n';
return 0;
}
//------------------------------
int main()
{
const char *c1 = "Hello ";
const char *c2 = "World";
char *r = new char[strlen(c1) + strlen(c2) + 1];
strcpy(r, c1);
strcat(r, c2);
cout << r << endl;

string s1 = "hello ";
string s2 = "World";
strcpy(r, (s1 + s2).c_str());
cout << r << endl;

delete[] r;
}
//--------------------------------
int main()
{
char c;
char *r = new char[20];
int i = 0;
while (cin.get(c)) {
if (isspace(c))
break;
r[i++] = c;
if (i == 20) {
cout << "要炸!" << endl;
break;
}
}
r[i] = 0;
cout << r << endl;
delete[] r;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: