pezy / cppprimer Goto Github PK
View Code? Open in Web Editor NEW:books: Solutions for C++ Primer 5th exercises.
Home Page: http://dwz.cn/cp5answer
License: Creative Commons Zero v1.0 Universal
:books: Solutions for C++ Primer 5th exercises.
Home Page: http://dwz.cn/cp5answer
License: Creative Commons Zero v1.0 Universal
When I try to compile ex_12_27_30_TEST.cpp, compiler complains that "back_inserter is not a member in std". And It turns out iterator header hasn't been included in this cpp yet. It's a minor offense at most. But fix it anyway.
The answer U give is
If the container holds elements of a class type and resize adds elements the element type must have a default constructor.
But I find the same sentence in the book, like this:
If the container holds elements of a class type and resize adds elements, we must supply an initializer or the element type must have a default constructor.
Which means we can supply an initializer and the default ctor isn't only way to the element of class type.
I write this code compiled in GCC 6.30:
#include <vector>
#include <iostream>
using namespace std;
class A
{
private:
int a;
public:
A() = delete;
A(int i): a(i) {}
friend int get_a(const A& object_A) { return object_A.a; };
};
int main(int argc, char const *argv[])
{
vector<A> vA(1, {123});
for (auto & i : vA)
{
cout << get_a(i) << endl;
}
cout << "After resize:" << endl;
vvi.resize(11, {123});
for (auto & i : vA)
{
cout << get_a(i) << endl;
}
return 0;
}
And thx for you to sharing the answers. :)
1.exercise 2.5 lose answer of (d)
2.exercise 2.6 your answer is “The first line's integer is decimal, the second line's integer is octal.”, but I think second line’s first integer isn’t octal . 9 doesn’t appear in Octal like that A doesn’t appear in decimal.
3.exercise 2.27 your answer think that “int *const p2 = &i2” is legal,
But if i2 is a variable of double type ,what’s the answer ?so it’s not strict .
So (d),(f) have same questions ,we don’t know i2 what type it is .
My English level is very poor , so can you understand what I want to express?thanks!
给出的答案如下:
int i; double d; const string *ps; char *pc; void *pv;
pv = (void*)ps; // pv = const_cast<string*>(ps); or pv = static_cast<void*>(const_cast<string*>(ps));
i = int(*pc); // i = static_cast<int>(*pc);
pv = &d; // pv = static_cast<void*>(&d);
pc = (char*)pv; // pc = reinterpret_cast<char*>(pv);
但自己看书理解后做题,第二行考虑到_pc和i一个是char一个是int,和reinterpret_cast部分的例子差不多,感觉应该用reinterpret_cast。
而第四行考虑到是从pv的void_类型变到pc的char*类型,和static_cast给的第二个例子一样,感觉应该用static_cast。
不知道我理解上是否有误?
想问下这个CppPrimer项目里的readme中第二行那个图片怎么生成的,那个图片中issues x open的数量还是随实际情况动态变化的。
while (cin >> curr) {
if (!isupper(curr[0]))
continue;
else if (prev == curr) {
cout << curr << " occurs twice in succession." << endl;
no_twice = true;
break;
}
else
prev = curr;
}
The first else
is redundant since the iteration will terminate once it hits (!isupper(curr[0]))
.
while (cin >> curr) {
if (!isupper(curr[0]))
continue;
if (prev == curr) {
cout << curr << " occurs twice in succession." << endl;
no_twice = true;
break;
}
else
prev = curr;
}
Pezy大神,首先很感谢您给像我这样的c++新手提供书上题目答案,非常感谢。
其次,我对于练习7.27中的Class中的display()方法有疑问,Screen类的width和height函数控制着contents的宽和高,而且类中有cursor成员,是不是暗示了"坐标"的概念?题目中的意思是不是打印contents的时候按坐标打印?如:
Screen& Screen::display(ostream &os)
{
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
os << contents[i*height + j];
}
os << endl;
}
return *this;
}
这样会不会更合理一些?谢谢解答!
d:/Source/CppPrimer/chapter08/ex8_6.cpp:15: undefined reference to read(std::istream&, Sales_data&)' d:/Source/CppPrimer/chapter08/ex8_6.cpp:17: undefined reference to
read(std::istream&, Sales_data&)'
d:/Source/CppPrimer/chapter08/ex8_6.cpp:19: undefined reference to Sales_data::combine(Sales_data const&)' d:/Source/CppPrimer/chapter08/ex8_6.cpp:21: undefined reference to
print(std::ostream&, Sales_data const&)'
d:/Source/CppPrimer/chapter08/ex8_6.cpp:25: undefined reference to `print(std::ostream&, Sales_data const&)'
其中有一个Blob articles = {"a","an","the"}//为何不会因为两步隐性类转换发生错误const char*到string以及std::initializer_list到Blob?
using std::string;
class test{
public:
test(std::initializer_list il) {}
test(string s) {};
};
int main()
{
test t = {"xyz"}; //通过编译
test a = "xyz"; //无法通过编译
return 0;
}
为什么会如此?
关于练习7.32:我用提供的代码在vs2015中编译,编译器提示警告:s.contents s.height s.width这三个不可访问。根据我看书的理解我觉得代码应该是对的,但是不知道是什么原因,会是编译器的问题嘛?
You should change the prev.
I think this function should be as below:
void f(forward_list<string> &lst, string s1, string s2){
auto prev = lst.before_begin();
auto curr = lst.begin();
bool flag = false;
while(curr!=lst.end()){
if (*curr == s1){
flag = true;
lst.insert_after(curr, s2);
return;
}
prev = curr;
curr++;
}
lst.insert_after(prev, s2);
}
template <typename T>
T abs(T i)
{
return i >= 0 ? i : -i;
}
题目说的是包含所有函数声明,您写的应该是定义吧?(如果我课本没理解错的话)
但是我在Chapter6.h
头文件里将您写的上面所示代码拷贝进去,然后又在我的main函数所在的cpp里这样写
int abs(int i)
{
return i >= 0 ? i : -i;
}
我在想,既然您用模板,那么我直接用int替换成实体,这样算不算重复定义?vs2013编译的时候,第一次,提示错误,说重复定义,但是奇怪的是,第二次编译的时候竟然不报错了,不知道怎么回事,求解答!
另外,您将函数名命名为abs,C++语言中本来就有abs函数,这样写好吗?我测试了一下,编译运行都能过,但是在调用abs函数时,编译器好像调用的是库里的abs函数,而不是我们自己写的。
最后,int fact(int val)
我在vs2013中是这么写的
#ifndef int fact(int val)
#endif
但是这样写老是会有警告信息,说**"warning C4067:预处理器指令后有意外标记 - 应输入换行符",google了一下说编译器发现预处理器指令之后有多余字符,并忽略它们**,刚开始我写的时候在fact(int val)
加了;
,我以为是这原因,将分号删了还有这警告,不知道这是为什么了?说 *ANSI 兼容性 * ,我只知道这是一种编码方式,但是我是在vs2013里直接写的,又不是在记事本上写的,为什么会出现这种情况呢?我真的无力了。
这样看起来舒服一点啊、、
不管是中文题:编写一个lambda,捕获一个局部int变量并递减变量值,直至它变为0
还是英文原文:Write a lambda that captures a local int variable and decrements that variable until it reaches 0.
怀疑对题意的理解可能出错
int local_val = 7;
auto decrement_to_zero = [&local_val](){
if (local_val == 0)
return true;
while (local_val > 0)
--local_val;
return false;
};
cout << decrement_to_zero() << endl;
中文:
中文版第455页(第十三章第二节第二小节定义行为像指针的类)
书上使用了引用计数来实现直接管理资源。
但是很显然这样管理资源异常复杂,对于类定义者也颇为不便。在C++11引入_shared_ptr_ 后似乎更没有这样做的理由,那为什么还要介绍这种方法呢?在什么情况下会用到这种方法呢(即使是在编译器支持C++11的情况下)?
其实这个issue发在这里不是太恰当……可能发邮件更合适
For English:
Page 514 on English edition(13.2.2 Defining Classes That Act Like Pointers).
The example from book use a reference count to manage resources rather than smart pointers. Clearly it's more complex(compare with smart pointers) and inconvenient for who designs class. It doesn't make any sense to use reference counts under C++0x standard so why the book introduce reference count? Under what circumstance should we use reference even if complier supports C++0x standard?
Exercise 2.21
Explain each of the following definitions. Indicate whether any are illegal and, if so, why.
int i = 0;
(b) int *ip = i;
这里(b)应该是合法的,i的值为0相当于空指针
https://github.com/pezy/CppPrimer/blob/master/ch06/ex6_42.cpp
题目要求end默认参数设置为”s”,但是success的复数形式是successes。
http://www.merriam-webster.com/dictionary/successes
The growth of the tourism industry is one of the city's great successes.
因此我认为作者的意思应该是,failure使用默认参数,但success要自己传”es“参数给end。
Exercise 13.1.4 ask for the member data is uniuqe serial number for numbered class. By looking your code.it could happens the identical numbers among different objects. as follow.
` numbered a, b = a, c = a;
f(a);//10
f(b);//11
f(c);//11
I think about one way to solve it. defined a static member data in numbered. First initializes zero to it outside class numbered. The static member initializes the unique serial number ,and then increment it, for whatever copy constructor or copy assignment-operator.
template<typename T,typename...args>
void print(const T& t, const args& ...rest)
{
if (!sizeof...(args))//参数包为空,只有一个参数t,终止递归
{
cout << t << endl;//没有分隔符
return;
}
cout << t << ", ";
print(rest...);
}
按照我的理解这样写只需要一个版本的print,rest...中的第一个参数将绑定到t,其余实参形成下一个print调用的参数包.但是编译的时候‘出现错误: error C2780: “void print(const T &,const args &...)”: 应输入 2 个参数,却提供了 0 个
class TreeNode
在习题13.28(a)中被定义为:
Exercise 13.28 defines class TreeNode
as follow:
class TreeNode {
private:
std::string value;
int count;
TreeNode* left;
TreeNode* right;
};
但是在 ex13_28.h 中class TreeNode
却被定义为:
While class TreeNode
defined in ex13_28.h is :
class TreeNode {
...
...
...
private:
std::string value;
int* count; // 私有成员 count 类型从 int 变为 int*
// Type of private memeber count changed from int to int*
TreeNode* left;
TreeNode* right;
};
是当时疏忽了吗?
重新看了一下,感觉这个count
是给TreeNode
记数的,这样的话,count
确实应该是int*
类型,可能是书漏印了?
Hello! pezy
I want to know why the "void" can not be "string".
code:
void makeLowercase(string& str)
{
for (auto& c : str)
if (isupper(c)) c = tolower(c);
}
Dear pezy, just now I tested your code of Exercise 10.25. I saw an error on the screen. Then I typed like this:
vector<int> ivec{ 1,2,3,4,5,6,7,8,9,10}; for (auto it = prev(ivec.end()); it != prev(ivec.begin()); --it) cout << *it << " "; cout << endl;
When I started debugging, the IDE told me that there was an error as out of range. I use Visual Studio 2015. Help!!! Please!!!
大神你好,看你的答案学习到了很多,现在有一个问题关于7.32.
我按照你给的代码在vs2015上,在clear函数体内的s.contents,s.height , s.width,编译器会显示警告不可访问。
不知道是什么问题。难道是编译器的问题?
Is the following code legal or not? If not, how might you make it legal?
int null = 0, *p = null;
illegal.
int null = 0, *p = nullptr;
this answer could not passed by compiler.
int null = 0, *p = &null;
but this was worked. is it correct?
what's the meaning of "preexited"?
In ex6_33_generics_version.cpp:
template<class T> void vector_print(const vector<T> &_v) { static typename vector<T>::const_iterator it = _v.begin(); cout << *it <<" "; ++it; if(it != _v.end()) { vector_print(_v); } }
If I tried void vector_print(const vector<T> _v)
(not reference), it will crash. (Windows + vs2013) I want to know why . (some tips : cout << *it++ <<" ";
replace cout << *it <<" "; ++it;
,maybe that's a better idea.)
string (&func(string (&arrStr)[10]))[10]
makes it complex .when I read it firstly,I cannot understand it .
Now as far as I know ,I think that string (&func())[10]
is easy to understand .Function func
can take 0 parameter .The right-left rule maybe help beginners like me to understand it.
练习9.48答案应该是2而不是string::nops
请问形参 string (&arrStr)[10] 是必要的嘛?
hey, pezy
I think list
is better than the others. We need to keep them alphabetical, thus we may need to insert elements in the middle frequently.
应该这样实现才行:
template <typename T, size_t N>
inline T* _begin(T (&a)[N]) {
// cout << "begin" << endl;
return a;
}
template <typename T, size_t N>
inline const T* _begin(const T (&a)[N]) {
// cout << "cbegin" << endl;
return a;
}
template <typename T, size_t N>
inline T* _end(T (&a)[N]) {
// cout << "end" << endl;
return a + N;
}
template <typename T, size_t N>
inline const T* _end(const T (&a)[N]) {
// cout << "cend" << endl;
return a + N;
}
hello, maybe
error: cout << (str1 <= str2 ? str1 : str2) << " is less than the other. "
right: cout << (str1.size() <= str2.size() ? str1 : str2) << " is less than the other. "
使用这两个头文件里面定义的东西是不是不需要加using std::size_t; using std::toupper; 之类的声明?
我看了您的几个答案中没有写,我实际尝试的时候,无论加不加都不影响。
(c) 是不是非法的?只能省略尾部的实参,这里省略了 wd 的,却没省略 bckgrnd 的。
209行和337行中 StrBlobPtr 和 ConstStrBlobPtr 的前缀递减运算符
check第一个参数是不是应该改成curr而不是-1...
因为题目是说输出text第一段,参见中文版P98(英文版P110)那段代码的注释是说一次输出text的每一行直至遇到第一个空白行为止
您的代码我没有弄错的话,应该是只将第一行字母变成大写,而不是题意中的将第一段变成大写(书中的一段应该指的是直到遇到第一个空白行之前的都算第一段)
我觉得正确的代码应该如下:
int main()
{
string tempStr;
vector text;
while (getline(cin, tempStr))
text.push_back(tempStr);
vector::iterator it;
for (auto it = text.begin(); it != text.end() && !(*it).empty(); ++it)
for (auto &c : *it)
c = toupper(c);
for (auto it = text.begin(); it != text.end(); ++it)
cout << *it << endl;
return 0;
}
如果弄错了,抱歉哈!
还有发issue,和pull request是不是没区别,我将你的这个project fork到我自己账户下,那么我在pull request里写这个问题,是不是您也能看到呢?
还有一个小问题,如果将我贴的代码变成代码片,我看我贴上的代码感觉就是纯汉字格式那样(不知道您懂我描述的意思吗)
i!=j<k
你的回答是:if j<k
is true, means i != 1
, else means i != 0
.
但是exercise 4.3 说C++语言没有明确规定大多数二元符的求值顺序,给编译器留有优化的余地。
那么是不是意味着此题还有其他的解法。
如:
if i!=j
is true,1<k
,else 0<k
;虽然这样感觉很别扭,但是这种解析方式对不对呢?
which siginifies a negatation operation on that particular bit. The value of that particular bit is then -2147483648. 我觉得可能是拼写有错,siginifies应该是signifies ,negatation应该是negation
这个结果好像是编译器不同,输出结果不一样,long double
在vs2013分配的是8字节.
您说的cout << sizeof(p)/sizeof(*p) << endl;
的结果依据32bit机器还是64bit机器,这里的machine指的是编译器还是用的电脑呢?我电脑是64位系统,但是用vs2013(32bit版)得到的结果是1。
postfix will copy itself as return, then increment or decrement. prefix will increment or decrement first, and return itself. so prefix is more effective in this program.(reduce one copy space.)
您画线的回答有错吗?我觉得没有错误,为何划去呢?
The postfix operator must store the original value so that it can return the unincremented value as its result. If we don’t need the unincremented value, there’s no need for the extra work done by the postfix operator.
这里不是也说了使用后缀++/--需要存储空间去存储原值,如果后面没有用到该原值,则没有必要使用后缀,所以正如你所说书上给的例子没有体现出区别.书上建议我们使用prefix,但是prefix和postfix还是有区别的,区别就是您画线说的,我这样理解对吗?
在您的注释里说:ival promoted to double
我觉得这种说法有点不恰当,不应该用promoted,书上说整形提升,是负责把小整数类型转换成较大的整数类型。short-->int 用promoted比较恰当,int-->double ,是不是用convert更加确切一点呢?毕竟double是浮点型。
我是初读c++primer,如有错误,请见谅!
print(j)
编译不通过,存在二义性?
void print(const int *pi);
void print(int (&arr)[2]);
int j[2]={0,1};
print(j);
Some functions declared in ex7_26.h are definited in ex7_26.cpp. it's no problem as to exercise7.26.
But exercise 8.6 - 8.8 include the head file "ex7_26.h", without those definitions, exercise 8.6-8.8 can't run correctly.
第二章的练习2.31的第一个r1=v2应该是illegal的啊,这题不是用2.30里的声明么,2.30里v2是const int的,r1是int &的,所以是不行的啊
(Question 2.31 in book) > r1 = v2; // legal, top-level const in v2 is ignored.
comments may be //illegal, reference to common interage cannot bind const interage.
我copy下来编译后运行说不支持的16位应用程序,这是为何呢?另外为什么不用
std::ostream& operator<<(std::ostream& os, const String& s) { auto p = s.elements; while (p != s.end) os << *p++; return os; }
而是用这个来重载呢
std::ostream& operator<<(std::ostream& os, const String& s) { char* c = const_cast<char*>(s.c_str()); while (*c != '\0') os << *c++; return os; }
关于练习13_48其中的String s5 = baz()会触发拷贝构造函数吗?vs2008有触发,但Mingw5.3.0 没触发
the fixed should be rem(i%j)
Do you mean 1.01 (double literal) is not an object,so the reference can't be bound to 1.01?
But const int &i=1.01
is valid.So i think the necessity of const should be the answer.
This is question I asked in SO,there are some answers, but I can't understand it .
为了便于清楚的表达我的疑惑之处,我还是用中文描述一下。
书上说constexpr
函数有几项约定:函数的返回类型及所有形参的类型都得是LiteralType。其实我一直以为LiteralType
就是1
,“hello”
这样的,但是看了那个链接,里面那个Requirements是表达什么意思呢?(英语渣渣没看懂)
但是然后他又说允许constexpr
函数的返回值并非一个常量:
// scale(arg) is a constant expression if arg is a constant expression constexpr size_t scale(size_t cnt) { return new_sz() * cnt; }
然后看了constant expression这个概念,直接把我看晕了,之前以为以为被const
修饰的表达式即是constant expression
,但看了一下,里面一大堆constant expression
的分类,我就不知道到底什么是constant expression
了。
根据 @ Mike Seymour 在评论里说的,size_t
是LiteralType
,所以函数返回类型是LiteralType
,但是我又搞不明白了,return
这个返回值不是LiteralType
吧,这是怎么回事呢?求指点迷津!
另外插一句,是不是一个人在对同一个repository一次最多只能开一个issue?我发现我想重新开一个issue问其他章的问题,直接变成重新编辑这个issue了
Why p1 = &arr[0];
and p2 = &arr[0].
?
These pointers can point to different elements of the array (for example p1 = &arr[1];
, p2 = &arr[3];
).
运行答案中代码(第一段):
Quote& r = q;
r.debug();
std::cout << "\n";
r = bq;
r.debug();
std::cout << "\n";
r = lq;
r.debug();
std::cout << "\n";
输出为:
data members of this class:
bookNo= aaa price= 10.6
data members of this class:
bookNo= bbb price= 111
data members of this class:
bookNo= ccc price= 222
我添加如下形式的代码(第二段):
Quote &r1 = q;
r1.debug();
std::cout << "\n";
Quote &r2 = bq;
r2.debug();
std::cout << "\n";
Quote& r3 = lq;
r3.debug();
std::cout << "\n";
输出为:
data members of this class:
bookNo= aaa price= 10.6
data members of this class:
bookNo= bbb price= 111 min_qty= 10 discount= 0.3
data members of this class:
bookNo= ccc price= 222 max_qty= 10 discount= 0.3
我添加如下形式的代码(第三段):
Quote &r4 = lq;
r4.debug();
std::cout << "\n";
r4 = bq;
r4.debug();
std::cout << "\n";
r4 = q;
r4.debug();
std::cout << "\n";
输出为:
data members of this class:
bookNo= ccc price= 222 max_qty= 10 discount= 0.3
data members of this class:
bookNo= bbb price= 111 max_qty= 10 discount= 0.3
data members of this class:
bookNo= aaa price= 10.6 max_qty= 10 discount= 0.3
我添加如下形式的代码(第四段):
Quote &r = q;
r.debug();
std::cout << "\n";
r = bq;
r.debug();
std::cout << "\n";
r = lq;
r.debug();
std::cout << "\n";
Quote &r5 = q;
r5.debug();
std::cout << "\n";
输出为:
data members of this class:
bookNo= aaa price= 10.6
data members of this class:
bookNo= bbb price= 111
data members of this class:
bookNo= ccc price= 222
data members of this class:
bookNo= ccc price= 222
上面四段代码是一段段单独运行的。
为什么第一段代码中,bq,lq的两个属性没有输出?
为什么第三段代码中,q会输出他没有的两个属性的值?
为什么第四段代码中,r5会输出lq的值?
为什么会这样,还请麻烦解释一下,谢谢!!!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.