#include <iostream>
#include <string>
using namespace std;
class Sales_item
{
friend std::istream& operator>>(std::istream&, Sales_item& );
friend std::ostream& operator<<(std::ostream&, const Sales_item&);
friend bool operator<(const Sales_item&,const Sales_item&);
friend bool operator==(const Sales_item&,const Sales_item&);
public:
Sales_item() = default;
Sales_item(const std::string& book): bookNo(book){}
Sales_item(std::istream& is){is >> *this; }
public:
Sales_item& operator+=(const Sales_item&);
std::string isbn() const { return bookNo; }
double avg_price() const;
private:
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
public:
};
inline bool compareIsbn(const Sales_item& lhs, const Sales_item& rhs)
{
return lhs.isbn() == rhs.isbn();
}
Sales_item operator+(const Sales_item&,const Sales_item&);
inline bool operator==(const Sales_item& lhs,const Sales_item& rhs)
{
return lhs.units_sold == rhs.units_sold &&
lhs.revenue == rhs.revenue &&
lhs.isbn() == rhs.isbn();
}
inline bool operator!=(const Sales_item& lhs,const Sales_item& rhs)
{
return !(lhs == rhs);
}
Sales_item& Sales_item::operator+=(const Sales_item& rhs)
{
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
Sales_item operator+(const Sales_item& lhs,const Sales_item& rhs)
{
Sales_item ret(lhs);
ret += rhs;
return ret;
}
std::istream& operator>>(std::istream& in, Sales_item& s)
{
double price;
in>>s.bookNo>>s.units_sold>>price;
if(in)
s.revenue = s.units_sold * price;
else
s = Sales_item();
return in;
}
std::ostream& operator<<(std::ostream& out,const Sales_item& s)
{
out<<s.isbn()<<" "<<s.units_sold<<" "
<<s.revenue<<" "<<s.avg_price();
return out;
}
double Sales_item::avg_price() const
{
if(units_sold)
return revenue / units_sold;
else
return 0;
}
#include <string>
#include <iostream>
class Sales_data
{
friend Sales_data add(const Sales_data&, const Sales_data&);
friend std::ostream &print(std::ostream&, const Sales_data&);
friend std::istream &read(std::istream&, Sales_data&);
public:
Sales_data() = default;
Sales_data(const std::string &s):bookNo(s){}
Sales_data(const std::string &s, unsigned n, double p):
bookNo(s),units_sold(n),revenue(p*n){}
Sales_data(std::istream &);
std::string isbn() const { return bookNo; }
Sales_data& combine(const Sales_data&);
double avg_price() const;
private:
public:
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
Sales_data add(const Sales_data&, const Sales_data&);
std::ostream &print(std::ostream&, const Sales_data&);
std::istream &read(std::istream&, Sales_data&);
inline bool compareIsbn(const Sales_data &lhs,const Sales_data &rhs)
{
return lhs.isbn() < rhs.isbn();
}
Sales_data::Sales_data(std::istream &is)
{
read(is, *this);
}
double Sales_data::avg_price() const
{
if(units_sold)
return revenue / units_sold;
else
return 0;
}
Sales_data& Sales_data::combine(const Sales_data &rhs)
{
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
Sales_data add(const Sales_data& lhs, const Sales_data &rhs)
{
Sales_data sum = lhs;
sum.combine(rhs);
return sum;
}
istream& read(istream &is, Sales_data &item)
{
double price = 0;
is >> item.bookNo>>item.units_sold>>price;
item.revenue = price * item.units_sold;
return is;
}
ostream& print(ostream &os, const Sales_data &item)
{
os << item.isbn()<<" "<<item.units_sold<<" "
<< item.revenue <<" "<<item.avg_price();
return os;
}
int gcd(int v1,int v2)
{
while(v2)
{
int temp = v2;
v2 = v1 % v2;
v1 = temp;
}
return v1;
}
int fact(int val)
{
int ret = 1;
while(val > 1)
ret *= val--;
return ret;
}
int factorial(int val)
{
if(val > 1)
return factorial(val - 1) * val;
return 1;
}
#if 0
int main()
{
return 0;
}
#include <iostream>
int main()
{
std::cout<<"Enter two numbers:"<<std::endl;
int v1 = 0,v2 = 0;
std::cin>>v1>>v2;
std::cout<<"The sum of "<<v1<<" and "<<v2
<<" is "<<v1 + v2<<std::endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
Enter two numbers:
12 2
The sum of 12 and 2 is 14
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
using namespace std;
int main()
{
cout<<"Hello,World"<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
Hello,World
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
int main()
{
std::cout<<"Enter two numbers: "<<std::endl;
int v1 = 0,v2 = 0;
std::cin>>v1>>v2;
std::cout<<"The sum of "<<v1<<" X "<<v2
<<" is "<<v1 * v2<<std::endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
Enter two numbers:
12 2
The sum of 12 X 2 is 24
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
int main()
{
int sum = 0,val = 0;
while(val <= 10)
{
sum += val;
++val;
}
std::cout<<"Sum of 1 and 10 inclusive is "<<sum<<std::endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
Sum of 1 and 10 inclusive is 55
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
int main()
{
int sum = 0;
for(int i = -100; i<=100;++i)
{
sum += i;
}
std::cout<<sum<<std::endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
0
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
int main()
{
int sum = 0,value = 0;
while(std::cin>>value)
{
sum += value;
}
std::cout<<"Sum is: "<<sum<<std::endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
1 2 2 3 12
Sum is: 20
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
int main()
{
int currVal = 0,val = 0;
if(std::cin >> currVal)
{
int cnt = 1;
while(std::cin>>val)
{
if(val == currVal)
++cnt;
else
{
std::cout<<currVal <<" occurs "
<<cnt<<" times "<<std::endl;
currVal = val;
cnt = 1;
}
}
}
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
1 1 1 1 12 2 2 2 2 23 2 3 3 31 2 21 2 1 2
1 occurs 4 times
12 occurs 1 times
2 occurs 4 times
23 occurs 1 times
2 occurs 1 times
3 occurs 2 times
31 occurs 1 times
2 occurs 1 times
21 occurs 1 times
2 occurs 1 times
1 occurs 1 times
#include <iostream>
int main()
{
Sales_item book;
std::cin>>book;
std::cout<<book<<std::endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
0-1212-2121221 3 12.32
0-1212-2121221 3 36.96 12.32
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
int main()
{
Sales_item item1,item2;
std::cin>>item1>>item2;
std::cout<<item1+item2<<std::endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
121 12 12.12 121 13 12
121 25 301.44 12.0576
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
int main()
{
Sales_item item1,item2;
std::cin>>item1>>item2;
if(item2.isbn() == item1.isbn())
{
std::cout<<item2 + item1<<std::endl;
return 0;
}
else
{
std::cerr<<"Data must refer to same ISBN"<<std::endl;
return -1;
}
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
1221 12 12 1221 12 12
1221 24 288 12
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
1212 21 12 12 1221 2121
Data must refer to same ISBN
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
int main()
{
Sales_item total;
if(std::cin>>total)
{
Sales_item trans;
while(std::cin>>trans)
{
if(total.isbn() == trans.isbn())
total += trans;
else
{
std::cout<<total<<std::endl;
total = trans;
}
}
std::cout<<total<<std::endl;
}
else
{
std::cerr<<"No data?!"<<std::endl;
return -1;
}
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
11 1 1 11 2 1 12 1 1 12 12 1 12 1 1 13 12 12
11 3 3 1
12 14 14 1
13 12 144 12
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
int main()
{
int i = 42;
std::cout<<i<<std::endl;
if(i)
i = 0;
std::cout<<i<<std::endl;
bool b = 42;
std::cout<<b<<std::endl;
int j = b;
std::cout<<j<<std::endl;
double pi = 3.14;
std::cout<<pi<<std::endl;
j = pi;
std::cout<<j<<std::endl;
unsigned char c = -1;
i = c;
std::cout<<i<<std::endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
42
0
1
1
3.14
3
255
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
int main()
{
unsigned u = 10,u2 = 42;
std::cout<<u2 - u<<std::endl;
std::cout<<u - u2<<std::endl;
int i = 10,i2 = 42;
std::cout<<i2 - i<<std::endl;
std::cout<<i - i2<<std::endl;
u = 42;
i = 10;
std::cout<<i - u<<std::endl;
std::cout<<u - i<<std::endl;
u = 10;
i = -42;
std::cout<<i + i<<std::endl;
std::cout<<u + i<<std::endl;
i = 10;
std::cout<<"good"<<std::endl;
while(i >= 0)
{
std::cout<<i<<std::endl;
--i;
}
for(int i = 10;i >= 0; --i)
{
std::cout<<i<<std::endl;
}
for(unsigned u = 0; u <= 10; ++u)
{
std::cout<<u<<std::endl;
}
u = 11;
while(u > 0)
{
--u;
std::cout<<u<<std::endl;
}
u = 10;
i = -42;
if(i < u)
std::cout<<i<<std::endl;
else
std::cout<<u<<std::endl;
u = 42;u2 = 10;
std::cout<<u - u2<<std::endl;
std::cout<<u2 - u<<std::endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
32
4294967264
32
-32
4294967264
32
-84
4294967264
good
10
9
8
7
6
5
4
3
2
1
0
10
9
8
7
6
5
4
3
2
1
0
0
1
2
3
4
5
6
7
8
9
10
10
9
8
7
6
5
4
3
2
1
0
10
32
4294967264
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
int main()
{
std::cout<<"Hello World!";
std::cout<<"";
std::cout<<"\nCC\toptions\tfile.[cC]\n";
std::cout<<"a really,really long string literal "
"that spans two lines"<<std::endl;
std::cout<<'M'<<" "<<'\115'<<" "<<'\x4d'<<std::endl;
unsigned long long bigVal = -1ULL;
std::cout<<bigVal<<std::endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
Hello World!
CC options file.[cC]
a really,really long string literal that spans two lines
M M M
18446744073709551615
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s;
cin>>s;
cout<<s<<endl;
string s1,s2;
cin>>s1>>s2;
cout<<s1<<"---"<<s2<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
dsada
dsada
dsada dsasda
dsada---dsasda
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <string>
using namespace std;
int main()
{
string word;
while(cin>>word)
cout<<word<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
dsads dsa d sad a d sad a d as das d sa dsa dsa
dsads
dsa
d
sad
a
d
sad
a
d
as
das
d
sa
dsa
dsa
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <string>
using namespace std;
int main()
{
string line;
while(getline(cin,line))
{
cout<<line<<endl;
}
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
dsadsadsa
dsadsadsa
dsadsada
dsadsada
dsada
dsada
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <string>
using namespace std;
int main()
{
string line;
while(getline(cin,line))
{
if(!line.empty())
{
cout<<line<<"---"<<endl;
}
}
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
dsadsa
dsadsa---
dsada
dsada---
d
d---
dsadsa
dsadsa---
dsa
dsa---
dsa
dsa---
^C
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
#include <string>
using namespace std;
int main()
{
string line;
while(getline(cin,line))
{
if(line.size() > 80)
cout<<line<<endl;
}
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
dsadsad
sssssssssssssssssssssssssssssssssssssssssssssssssssssssssss
ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss
ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str("the expense of spirit\n");
cout<<"The size of "<<str<<" is "<<str.size()
<<" characters,including the newline"<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
The size of the expense of spirit
is 22 characters,including the newline
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <string>
#include <cctype>
#include <iostream>
using namespace std;
int main()
{
string s("Hello world!!!");
decltype(s.size()) punct_cnt = 0;
for(auto c : s)
{
if(ispunct(c))
++punct_cnt;
}
cout<<punct_cnt<<" punctuation characters in "<<s<<endl;
string orig = s;
for(auto &c : s)
{
c = toupper(c);
}
cout<<s<<endl;
s = orig;
decltype(s.size()) index = 0;
while(index != s.size() && !isspace(s[index]))
{
s[index] = toupper(s[index]);
index++;
}
cout<<s<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
3 punctuation characters in Hello world!!!
HELLO WORLD!!!
HELLO world!!!
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str("some string"),orig = str;
if(!str.empty())
{
cout<<str[0]<<endl;
}
if(!str.empty())
{
str[0] = toupper(str[0]);
}
cout<<str<<endl;
str = orig;
if(str.begin() != str.end())
{
auto it = str.begin();
*it = toupper(*it);
}
cout<<str<<endl;
str = orig;
for(auto it = str.begin(); it!=str.end() && !isspace(*it);++it)
{
*it = toupper(*it);
}
cout<<str<<endl;
str = orig;
decltype(str.size()) index = 0;
while(index != str.size() && isspace(str[index]))
{
str[index] = toupper(str[index]);
++index;
}
cout<<str<<endl;
auto beg = str.begin();
while(beg != str.end() && !isspace(*beg))
{
*beg = toupper(*beg);
++beg;
}
cout<<str<<endl;
str = orig;
for(auto c : str)
{
cout<<c<<endl;
}
for(auto &c : str)
c = '*';
cout<<str<<endl;
str = orig;
for(decltype(str.size()) ix = 0; ix != str.size();++ix)
{
cout << str[ix] << endl;
}
for(decltype(str.size()) ix = 0; ix != str.size(); ++ix)
{
str[ix] = '*';
}
cout<<str<<endl;
str = orig;
for(auto beg = str.begin(); beg != str.end();++beg)
{
cout<<*beg<<endl;
}
for(auto beg = str.begin(); beg != str.end(); ++beg)
{
*beg = '*';
}
cout<<str<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
s
Some string
Some string
SOME string
some string
SOME string
s
o
m
e
s
t
r
i
n
g
***********
s
o
m
e
s
t
r
i
n
g
***********
s
o
m
e
s
t
r
i
n
g
***********
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <string>
#include <iostream>
#include <cstring>
#include <cstddef>
using namespace std;
int main()
{
string s1 = "A string example";
string s2 = "A different string";
if(s1 < s2)
cout<<s1<<endl;
else
cout<<s2<<endl;
const char ca1[] = "A string example";
const char ca2[] = "A different string";
if(strcmp(ca1,ca2) < 0)
cout<<ca1<<endl;
else
cout<<ca2<<endl;
const char* cp1 = ca1, *cp2 = ca2;
cout<<strcmp(cp1,cp2)<<endl;
cout<<strcmp(cp2,cp1)<<endl;
cout<<strcmp(cp1,cp1)<<endl;
cout<<strlen(cp1)<<endl;
const unsigned sz = 16 + 18 + 2;
char largeStr[sz];
strcpy(largeStr,ca1);
strcpy(largeStr," ");
strcpy(largeStr,ca2);
cout<<largeStr<<endl;
strncpy(largeStr,ca1,sz);
if(strlen(ca1) > sz)
largeStr[sz-1] = '\0';
strncpy(largeStr," ",2);
strncpy(largeStr,ca2,sz - strlen(largeStr));
cout<<largeStr<<endl;
string large_string = s1 + " " + s2;
cout<<large_string<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
A different string
A different string
15
-15
0
16
A different string
A different string
A string example A different string
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
#include <string>
#include <cstddef>
using namespace std;
int main()
{
const string hexdigits = "0123456789ABCDEF";
cout<<"Enter a series of numbers between 0 and 15"
<<" separated by spaces. Hit ENTER when finished: "
<<endl;
string result;
string::size_type n;
while(cin>>n)
if(n < hexdigits.size())
result += hexdigits[n];
cout<<"Your hex number is: "<<result<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
Enter a series of numbers between 0 and 15 separated by spaces. Hit ENTER when finished:
12
Your hex number is: C
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
Enter a series of numbers between 0 and 15 separated by spaces. Hit ENTER when finished:
14
Your hex number is: E
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
Enter a series of numbers between 0 and 15 separated by spaces. Hit ENTER when finished:
15
Your hex number is: F
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <cstddef>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<unsigned> grades;
unsigned scores[11] = {};
unsigned grade;
while(cin >> grade)
{
if(grade<=100)
{
++scores[grade/10];
}
grades.push_back(grade);
}
cout<<"grades.size = "<<grades.size()<<endl;
for(auto g : grades)
{
cout<<g<<" ";
}
cout<<endl;
for(auto i : scores)
{
cout<<i<<" ";
}
cout<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
1 12 23 45 32 21 34 67 87 54 65 67 43 54 67
grades.size = 15
1 12 23 45 32 21 34 67 87 54 65 67 43 54 67
1 1 2 2 2 2 4 0 1 0 0
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> articles = {"a","an","the"};
vector<string> svec;
vector<int> ivec;
vector<Sales_item> Sales_vec;
vector<vector<string>> file;
vector<vector<int>> vecOfvec;
cout<<svec.size()<<" "<<ivec.size()<<" "
<<Sales_vec.size()<<" "
<<file.size()<<" "<<vecOfvec.size()<<endl;
vector<int> ivec2(10);
vector<int> ivec3(10,-1);
vector<string> svec2(10);
vector<string> svec3(10,"hi");
cout<<ivec2.size()<<" "<<ivec3.size()<<" "
<<svec2.size()<<" "<<svec3.size()<<endl;
vector<string> v1(10);
vector<string> v2{10};
vector<string> v3(10,"hi");
vector<string> v4{10,"hi"};
cout<<v1.size()<<" "<<v2.size()<<" "<<v3.size()<<" "
<<v4.size()<<endl;
vector<string> vs1{"hi"};
vector<string> vs2{10};
vector<string> vs3{10,"hi"};
cout<<vs1.size()<<" "<<vs2.size()<<" "<<vs3.size()<<endl;
vector<int> v5(10,1);
vector<int> v6{10,1};
cout<<v5.size()<<" "<<v6.size()<<endl;
vector<int> alt_v3 = {10};
vector<int> alt_v4 = {10,1};
cout<<alt_v3.size()<<" "<<alt_v4.size()<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
0 0 0 0 0
10 10 10 10
10 10 10 10
1 10 10
10 2
1 2
xz@xiaqiu:~/study/cpp-primer/study/build$
#include<string>
#include<vector>
#include<iostream>
using namespace std;
int main()
{
vector<unsigned> grades;
vector<unsigned> scores(11,0);
unsigned grade;
while(cin >> grade)
{
if(grade <= 100)
{
grades.push_back(grade);
++scores[grade/10];
}
}
cout<<"grades.size = "<<grades.size()<<endl;
for(auto it : grades)
cout<<it<<" ";
cout<<endl;
cout<<"scores.size = "<<scores.size()<<endl;
for(auto it : scores)
{
cout<<it<<" ";
}
cout<<endl;
vector<unsigned> alt_score(11,0);
for(auto it = grades.begin(); it != grades.end();++it)
{
unsigned i = *it;
++(*(alt_score.begin() + i/10));
}
cout<<"alt_scores.size = "<<alt_score.size()<<endl;
for(auto it = alt_score.begin();it != alt_score.end();++it)
{
cout<<*it<<" ";
}
cout<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
1 12 23 32 43 54 65 54 54 65 65 76 76 87 89 78 67 67 78 78 56
grades.size = 21
1 12 23 32 43 54 65 54 54 65 65 76 76 87 89 78 67 67 78 78 56
scores.size = 11
1 1 1 1 1 4 5 5 2 0 0
alt_scores.size = 11
1 1 1 1 1 4 5 5 2 0 0
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> text;
string s;
while(getline(cin,s))
text.push_back(s);
cout<<"text.size: "<<text.size()<<endl;
for(auto it = text.cbegin();
it != text.cend() && !(*it).empty(); ++it)
{
cout<<*it<<endl;
}
for(auto it = text.cbegin();
it != text.cend() && !it->empty(); ++it)
{
cout<<*it<<endl;
}
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
dsad asdsa dsa ds ad sa dsa dsad a
dsadsaaaaaaaaaaaaaaaaaaaaadsadadsad
dsadaddsadsadsadas
dsadsa
dsadsadsadsad dsadsadsa
dsadsad
text.size: 6
dsad asdsa dsa ds ad sa dsa dsad a
dsadsaaaaaaaaaaaaaaaaaaaaadsadadsad
dsadaddsadsadsadas
dsadsa
dsadsadsadsad dsadsadsa
dsadsad
dsad asdsa dsa ds ad sa dsa dsad a
dsadsaaaaaaaaaaaaaaaaaaaaadsadadsad
dsadaddsadsadsadas
dsadsa
dsadsadsadsad dsadsadsa
dsadsad
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int> v = {0,1,2,3,4,5,6,7,8,9};
auto sz = v.size();
decltype(sz) i = 0;
while(i != sz)
{
v.push_back(*v.begin() + i);
++i;
}
for(auto it:v)
cout<<it<<" ";
cout<<endl;
vector<int> alt_v = {0,1,2,3,4,5,6,7,8,9};
for(decltype(alt_v.size())i = 0,sz = alt_v.size();i!=sz;++i)
{
alt_v.push_back(alt_v[i]);
}
for(auto it : alt_v)
cout<<it<<" ";
cout<<endl;
vector<int> v2 = {0,1,2,3,4,5,6,7,8,9};
decltype(v2.size()) ix = 0;
while(ix != v2.size() && v2[ix] < 5)
{
v2[ix] = 0;
++ix;
}
for(unsigned i = 0; i!=v2.size();++i)
cout<<v2[i]<<" ";
cout<<endl;
vector<int>alt_v2 = {0,1,2,3,4,5,6,7,8,9};
auto it = alt_v2.begin();
while(it != alt_v2.end() && *it < 5)
{
*it = 0;
++it;
}
for(auto it = alt_v2.begin();
it != alt_v2.end();
++it)
cout<<*it<<" ";
cout<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
0 0 0 0 0 5 6 7 8 9
0 0 0 0 0 5 6 7 8 9
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <vector>
#include <iostream>
#include <cstddef>
using namespace std;
int main()
{
int ia1[3][4];
int arr[10][20][30] = {0};
ia1[2][3] = arr[0][0][0];
int (&row)[4] = ia1[1];
int ia2[3][4] = {
{0, 1, 2, 3},
{4, 5, 6, 7},
{8, 9, 10, 11}
};
int ia3[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
int ia4[3][4] = {{ 0 }, { 4 }, { 8 }};
int ix[3][4] = {0,3,6,9};
cout<<ix[0][3]<<' '<<ix[1][0]<<' '<<ix[2][0]<<endl;
constexpr size_t rowCnt = 3,colCnt = 4;
int ia[rowCnt][colCnt];
for(size_t i = 0; i != rowCnt; ++i)
{
for(size_t j = 0; j != colCnt; ++j)
{
ia[i][j] = i * colCnt + j;
}
}
for(const auto &row : ia)
{
for(auto col : row)
{
cout<<col<<" ";
}
cout<<endl;
}
cout<<ia[0][0]<<' '<<ia[2][3]<<endl;
for(auto p = ia; p != ia + rowCnt; ++p)
{
for(auto q = *p; q != *p+colCnt;++q)
cout<<*q<<' ';
cout<<endl;
}
for(auto p = begin(ia); p!=end(ia);++p)
{
for(auto q = begin(*p); q!=end(*p);++q)
{
cout<<*q<<' ';
}
cout<<endl;
}
using int_array = int[4];
for(int_array *p = ia; p != ia + 3;++p)
{
for(int *q = *p; q != *p + 4;++q)
{
cout<<*q<<' ';
}
cout<<endl;
}
int alt_ia[rowCnt][colCnt];
size_t cnt = 0;
for(auto &row : alt_ia)
{
for(auto &col : row)
{
col = cnt;
++cnt;
}
}
for(const auto& row : alt_ia)
{
for(auto col : row)
cout<<col<<" ";
}
cout<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
9 0 0
0 1 2 3
4 5 6 7
8 9 10 11
0 11
0 1 2 3
4 5 6 7
8 9 10 11
0 1 2 3
4 5 6 7
8 9 10 11
0 1 2 3
4 5 6 7
8 9 10 11
0 1 2 3 4 5 6 7 8 9 10 11
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
using namespace std;
int main()
{
cout<<-30 * 3 + 21 / 5<<endl;
cout<<-30 + 3 * 21 / 5<<endl;
cout<<30 / 3 * 21 % 5<<endl;
cout<<30 / 3 * 21 % 4<<endl;
cout<<-30 / 3 * 21 % 4<<endl;
cout<<12 / 3 * 4 + 5 * 15 + 24 % 4 / 2<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
-86
-18
0
2
-2
91
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
#include <cstddef>
using namespace std;
int ia[] = {1,2,3,3,4,5,6};
int main()
{
constexpr size_t sz = sizeof(ia) / sizeof(*ia);
int arr2[sz];
cout<<"ia size: "<<sz<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
ia size: 7
ia size: 7
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<unsigned> grades;
int main()
{
unsigned i;
while(cin>>i)
{
grades.push_back(i);
}
for(auto grade : grades)
{
string finalgrade = (grade < 60) ? "fail":"pass";
finalgrade = (grade > 90) ? "high pass" : (grade < 60) ? "fail" : "pass";
cout<<grade<<" " + finalgrade<<endl;
}
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
1 23 34 56 56 67 67 87 76 76 87 90 100 92 99
1 fail
23 fail
34 fail
56 fail
56 fail
67 pass
67 pass
87 pass
76 pass
76 pass
87 pass
90 pass
100 high pass
92 high pass
99 high pass
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <cstddef>
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
string &tolower(string &s)
{
for(auto &i : s)
{
i = tolower(i);
}
return s;
}
string &toupper(string &s)
{
for(auto &i : s)
i = toupper(i);
return s;
}
int main()
{
int i = 0;
cout<<i<<" "<<++i<<endl;
string s("a string"),orig = s;
cout<<toupper(s)<<endl;
cout<<tolower(s)<<endl;
s = orig;
cout<<toupper(s)<<" "<<tolower(s)<<endl;
string first = toupper(s);
string second = tolower(s);
cout<<first<<" "<<second<<endl;
cout<<second<<" "<<first<<endl;
cout<<first<<" "<<first<<endl;
cout<<second<<" "<<second<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
0 1
A STRING
a string
A STRING a string
A STRING a string
a string A STRING
A STRING A STRING
a string a string
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
using namespace std;
int main()
{
short short_value = 32767;
short_value += 1;
cout<<"short_value "<<short_value<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
short_value -32768
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
using namespace std;
int main()
{
Sales_data data, *p;
sizeof(Sales_data);
sizeof data;
sizeof p;
sizeof *p;
sizeof data.revenue;
sizeof Sales_data::revenue;
cout<<"short: "<<sizeof(short)<<"\n"
<<"short[3]: "<<sizeof(short[3])<<"\n"
<<"short*: "<<sizeof(short*)<<"\n"
<<"short&: "<<sizeof(short&)<<endl;
cout<<endl;
cout<<"int: "<<sizeof(int)<<"\n"
<<"int[3]: "<<sizeof(int[3])<<"\n"
<<"int*: "<<sizeof(int*)<<"\n"
<<"int&: "<<sizeof(int&)<<endl;
cout<<endl;
cout<<"Sales_data: "<<sizeof(Sales_data)<<"\n"
<<"Sales_data[3]: "<<sizeof(Sales_data[3])<<"\n"
<<"Sales_data*: "<<sizeof(Sales_data*)<<"\n"
<<"Sales_data&: "<<sizeof(Sales_data&)<<endl;
cout<<"Sales_data::revenue: "<<sizeof Sales_data::revenue<<"\n"
<<"data.revenue: "<<sizeof data.revenue<<endl;
int x[10];
int *ip = x;
cout<<sizeof(x)/sizeof(*x)<<endl;
cout<<sizeof(ip)/sizeof(*ip)<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
short: 2
short[3]: 6
short*: 8
short&: 2
int: 4
int[3]: 12
int*: 8
int&: 4
Sales_data: 48
Sales_data[3]: 144
Sales_data*: 8
Sales_data&: 48
Sales_data::revenue: 8
data.revenue: 8
10
2
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
using namespace std;
int main()
{
int i = 1024;
int k = -i;
bool b = true;
bool b2 = -b;
cout<<b<<" "<<b2<<" "<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
1 1
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <cstddef>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int> ivec;
int cnt = 10;
while(cnt > 0)
ivec.push_back(cnt--);
auto iter = ivec.begin();
while(iter != ivec.end())
cout<<*iter++<<" ";
std::cout<<std::endl;
vector<int> vec2(10,0);
cnt = vec2.size();
for(vector<int>::size_type ix = 0;
ix != vec2.size(); ++ix,--cnt)
vec2[ix] = cnt;
iter = vec2.begin();
while(iter != vec2.end())
cout<<*iter++<<" ";
std::cout<<std::endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int ival = 3.541 + 3;
cout<<ival<<endl;
return 0;
}
#include <stdexcept>
#include <iostream>
#include "Sales_item.h"
using namespace std;
int main()
{
Sales_item item1,item2;
while(cin>>item1>>item2)
{
try
{
if(item1.isbn() != item2.isbn())
throw runtime_error("数据必须引用相同的 ISBN");
cout<<item1 + item2<<endl;
}
catch(runtime_error err)
{
cout<<err.what()<<"\n再试一次? 输入 y 或 n"<<endl;
char c;
cin>>c;
if(!cin || c == 'n')
break;
}
}
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
string rsp;
do
{
cout<<"请输入两个值:";
int val1 = 0,val2 = 0;
cin>>val1>>val2;
cout<<"总数是 "<<val1<<" 和 "<<val2
<<" = "<<val1 + val2<<"\n\n"
<<"更多的? 输入yes 或 n: ";
cin>>rsp;
}while(!rsp.empty() && rsp[0] != 'n');
cout<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
请输入两个值:231 32
总数是 231 和 32 = 263
更多的? 输入yes 或 n: yes
请输入两个值:321 342
总数是 321 和 342 = 663
更多的? 输入yes 或 n: n
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
#include <vector>
#include <string>
using namespace std;
const vector<string> scores = {"F", "D", "C", "B", "A", "A++"};
vector<unsigned> grades;
string goodVers(string lettergrade, unsigned grade)
{
if(grade % 10 > 7)
lettergrade += '+';
else
if(grade % 10 < 3)
lettergrade += '-';
return lettergrade;
}
string badVers(string lettergrade,unsigned grade)
{
if(grade % 10 >= 3)
if(grade % 10 > 7)
lettergrade += '+';
else
lettergrade += '-';
return lettergrade;
}
string rightVers(string lettergrade, unsigned grade)
{
if(grade % 10 >= 3)
{
if(grade % 10 > 7)
lettergrade += '+';
}
else
lettergrade += '-';
return lettergrade;
}
int main()
{
unsigned grade;
while(cin>>grade)
grades.push_back(grade);
for(auto it : grades)
{
cout<<it<<" ";
string lettergrade;
if(it < 60)
lettergrade = scores[0];
else
{
lettergrade = scores[(it - 50) / 10];
if(it != 100)
lettergrade += '+';
else if(it % 10 < 3)
lettergrade += '-';
}
cout<<lettergrade<<endl;
if(it > 59 && it != 100)
{
cout<<"替代版本:"<<it<<" ";
lettergrade = scores[(it - 50)/10];
cout<<goodVers(lettergrade,it)<<" ";
cout<<badVers(lettergrade,it)<<" ";
cout<<rightVers(lettergrade,it)<<" ";
cout<<endl;
}
}
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
12 23 54 56 7 87 98 99 89 97 96 54 4 65 34
12 F
23 F
54 F
56 F
7 F
87 B+
替代版本:87 B B- B
98 A+
替代版本:98 A+ A+ A+
99 A+
替代版本:99 A+ A+ A+
89 B+
替代版本:89 B+ B+ B+
97 A+
替代版本:97 A A- A
96 A+
替代版本:96 A A- A
54 F
4 F
65 D+
替代版本:65 D D- D
34 F
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
using namespace std;
int main()
{
char ch;
unsigned vowelCnt = 0;
unsigned otherCnt = 0;
while(cin >> ch)
{
switch(ch)
{
case 'a': case 'e': case 'i': case 'o': case 'u':
++vowelCnt;
break;
default:
++otherCnt;
break;
}
}
cout << "元音数: \t" << vowelCnt << '\n'
<< "非元音总数: \t" << otherCnt << '\n';
return 0;
}
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<int> ivec;
vector<int> v = {0,1,2,3,4,5,6,7,8,9};
for(auto &r : v)
r *= 2;
for(int r : v)
cout<<r<<" ";
cout<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
0 2 4 6 8 10 12 14 16 18
xz@xiaqiu:~/study/cpp-primer/study/build$
#include<iostream>
using namespace std;
int main()
{
unsigned aCnt = 0,eCnt = 0,iCnt = 0,oCnt = 0,uCnt = 0;
char ch;
while(cin >> ch)
{
switch(ch)
{
case 'a':
++aCnt;
break;
case 'e':
++eCnt;
break;
case 'i':
++iCnt;
break;
case 'o':
++oCnt;
break;
case 'u':
++uCnt;
break;
}
}
cout << "元音数 a: \t" << aCnt << '\n'
<< "元音数 e: \t" << eCnt << '\n'
<< "元音数 i: \t" << iCnt << '\n'
<< "元音数 o: \t" << oCnt << '\n'
<< "元音数 u: \t" << uCnt << endl;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
ewqewqretgrfsadxzxczvcxvcxzdsadfsfdffedfrrgtrjyjukiuihnhggfbfdvdfw
元音数 a: 2
元音数 e: 4
元音数 i: 2
元音数 o: 0
元音数 u: 2
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <cstddef>
#include <iostream>
using namespace std;
#define DSADSA
int arr[10];
int *p1[10];
int (*p2)[10] = &arr;
using arrT = int[10];
arrT* func(int i);
auto func(int i)->int(*)[10];
int (*func(int i))[10];
auto func2(int i)->int(&)[10];
int odd[] = {1,3,5,7,9};
int even[] = {0,2,4,6,8};
int *elemPtr(int i)
{
return (i % 2) ? odd : even;
}
decltype(odd) *arrPtr(int i)
{
return (i % 2) ? &odd : &even;
}
int (&arrRef(int i))[5]
{
return (i % 2) ? odd : even;
}
int main()
{
int *p = elemPtr(6);
int (*arrP)[5] = arrPtr(5);
int (&arrR)[5] = arrRef(4);
for(size_t i = 0; i < 5; ++i)
{
cout<<p[i]<<" ";
}
std::cout<<std::endl;
for(size_t i = 0; i < 5; ++i)
{
cout<<(*arrP)[i]<<" ";
}
std::cout<<std::endl;
for(size_t i = 0; i < 5; ++i)
{
cout<<arrR[i]<<" ";
}
std::cout<<std::endl;
return 0;
}
#include <cstddef>
#include <iostream>
using namespace std;
size_t count_calls()
{
static size_t ctr = 0;
return ++ctr;
}
int main()
{
for(size_t i = 0; i != 10; ++i)
cout<<count_calls()<<" ";
cout<<endl;
return 0;
}
#include <vector>
#include <string>
#include <iostream>
#include <initializer_list>
#include <sstream>
using namespace std;
struct ErrCode
{
ErrCode(int i) : num(i){}
string msg()
{
ostringstream s;
s<<"ErrCode "<<num;
return s.str();
}
int num;
};
void error_msg(initializer_list<string> il)
{
for(auto beg = il.begin(); beg != il.end(); ++beg)
cout<<*beg<<" ";
cout<<endl;
}
void error_msg(ErrCode e, initializer_list<string> il)
{
cout<<e.msg()<<": ";
for(const auto &elem : il)
cout<<elem<<" ";
cout<<endl;
}
vector<string> functionX()
{
string expected = "description",
actual = "some other case";
if(expected.empty())
return {};
else if(expected == actual)
return {"functionX","okay"};
else
return {"functionX",expected,actual};
}
int main()
{
string expected = "description",actual = "some other case";
initializer_list<int> li = {0,1,2,3};
if(expected != actual)
error_msg({"functionX",expected,actual});
else
error_msg({"functionX","okay"});
if(expected != actual)
error_msg(ErrCode(42),{"functionX",expected,actual});
else
error_msg(ErrCode(0),{"functionX","okay"});
error_msg({});
auto result = functionX();
for(auto i : result)
cout<<i<<" ";
cout<<endl;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
functionX description some other case
ErrCode 42: functionX description some other case
functionX description some other case
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
int main()
{
cout<<factorial(5)<<endl;
cout<<fact(5)<<endl;
cout<<factorial(0)<<endl;
cout<<fact(0)<<endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
string::size_type sumLength(const string&, const string&);
string::size_type largerLength(const string&, const string&);
string::size_type sumLength(const string& s1,const string &s2)
{
return s1.size() + s2.size();
}
string::size_type largerLength(const string &s1, const string &s2)
{
return (s1.size() > s2.size()) ? s1.size() : s2.size();
}
decltype(sumLength) *getFcn(const string&);
auto getFcn(const string&) -> string::size_type(*)(const string&, const string&);
string::size_type (*getFcn(const string &))(const string&, const string&);
decltype(sumLength)*
getFcn(const string& fetch)
{
if(fetch == "sum")
return sumLength;
return largerLength;
}
int main()
{
cout<<getFcn("sum")("hello","world!")<<endl;
cout<<"--------------"<<endl;
cout<<getFcn("larget")("hello","world")<<endl;
return 0;
}
#include <iterator>
#include <iostream>
#include <cstddef>
using namespace std;
void print(const int ia[], size_t size)
{
for(size_t i = 0; i != size; ++i)
{
cout<<ia[i]<<" ";
}
cout<<endl;
}
int main()
{
int j[] = {0,1,2,3,4,5,6,7,8,9};
print(j,end(j) - begin(j));
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
0 1 2 3 4 5 6 7 8 9
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <string>
#include <iostream>
using namespace std;
inline const string &
shorterString(const string& s1, const string &s2)
{
return s1.size() <= s2.size() ? s1 : s2;
}
int main()
{
string s1("successes"),s2("failure");
cout<<shorterString(s1,s2)<<endl;
cout<<shorterString(s1,s2).size()<<endl;
}
#include <cstdlib>
int main()
{
bool some_failure = false;
if(some_failure)
return EXIT_FAILURE;
else
return EXIT_SUCCESS;
}
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
short i = 65537;
int j = i + 1;
cout<<bitset<32>(65537)<<endl;
cout<<i<<endl;
cout<<bitset<32>(65538)<<endl;
cout<<j<<endl;
bitset<sizeof(short)*8>shortSet;
shortSet.set();
cout<<shortSet<<endl;
cout<<(int)(shortSet.to_ulong())<<endl;
cout<<(short)(shortSet.to_ulong())<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/1$ ./1
00000000000000010000000000000001
1
00000000000000010000000000000010
2
1111111111111111
65535
-1
xz@xiaqiu:~/study/cpp-primer/study/1$
#include <stdio.h>
class A
{
public:
void test(){printf("test A\nthis = %d\n",this);}
};
int main()
{
A *pA = NULL;
pA->test();
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/1$ ./2
test A
this = 0
xz@xiaqiu:~/study/cpp-primer/study/1$
#include <iostream>
#include <typeinfo>
#include <cxxabi.h>
using namespace std;
string getClearName(const char* name)
{
int status = -1;
char* clearName = abi::__cxa_demangle(name,NULL,NULL,&status);
const char* const demangledName = (status == 0)?clearName : name;
string ret_val(demangledName);
free(clearName);
return ret_val;
}
int main()
{
int a[2][2][3] = {{{1,2,3},{4,5,6}},{{7,8,9},{10,11,12}}};
int *ptr = (int*)(&a+1);
printf("%d %d\n", *(int*)(a + 1), *(ptr - 1));
cout<<getClearName(typeid(ptr).name())<<endl;
cout<<getClearName(typeid(a).name())<<endl;
cout<<getClearName(typeid(&a).name())<<endl;
cout<<"-------------------------------"<<endl;
cout<<getClearName(typeid(a+1).name())<<endl;
cout<<getClearName(typeid(&a+1).name())<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/1$ ./3
7 12
int*
int [2][2][3]
int (*) [2][2][3]
-------------------------------
int (*) [2][3]
int (*) [2][2][3]
xz@xiaqiu:~/study/cpp-primer/study/1$
#include <iostream>
#include <typeinfo>
#include <cxxabi.h>
using namespace std;
string getClearName(const char* name)
{
int status = -1;
char* clearName = abi::__cxa_demangle(name,NULL,NULL,&status);
const char* const demangledName = (status == 0)?clearName : name;
string ret_val(demangledName);
free(clearName);
return ret_val;
}
int main()
{
static char* s[] = {"black","white","pink","violet"};
char **ptr[] = {s+3,s+2,s+1,s}, ***p;
p = ptr;++p;
printf("%s\n",*(s));
printf("%s\n",*(s+1));
printf("%s\n",*(s+2));
printf("%s\n",*(s+3));
printf("%s\n",(**p)+1);
cout<<"------------------------"<<endl;
cout<<getClearName(typeid(s).name())<<endl;
cout<<getClearName(typeid(s+1).name())<<endl;
cout<<getClearName(typeid(p).name())<<endl;
cout<<getClearName(typeid(ptr).name())<<endl;
cout<<getClearName(typeid(**p).name())<<endl;
cout<<getClearName(typeid((**p)+1).name())<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/1$ ./4
black
white
pink
violet
ink
------------------------
char* [4]
char**
char***
char** [4]
char*
char*
xz@xiaqiu:~/study/cpp-primer/study/1$
static char* s[] = {"black","white","pink","violet"};
--------------------------------------------
|s[0]|--------->"black"
|s[1]|--------->"white"
|s[2]|--------->"pink"
|s[3]|--------->"violet"
--------------------------------------------
s = s[0]
s+1 = s[1]
s+2 = s[2]
s+3 = s[3]
char **ptr[] = {s+3,s+2,s+1,s};
|ptr[0]|------->|s[3]|--------->"violet"
|ptr[1]|------->|s[2]|--------->"pink"
|ptr[2]|------->|s[1]|--------->"white"
|ptr[3]|------->|s[0]|--------->"black"
***p
p = ptr;
p------->|ptr[0]|------->|s[3]|--------->"violet"
|ptr[1]|------->|s[2]|--------->"pink"
|ptr[2]|------->|s[1]|--------->"white"
|ptr[3]|------->|s[0]|--------->"black"
++p;
|ptr[0]|------->|s[3]|--------->"violet"
p------->|ptr[1]|------->|s[2]|--------->"pink"
|ptr[2]|------->|s[1]|--------->"white"
|ptr[3]|------->|s[0]|--------->"black"
(**p)+1
|ptr[0]|------->|s[3]|--------->"violet"
|ptr[1]|------->|s[2]|--------->"pink"<----------(**p)
|ptr[2]|------->|s[1]|--------->"white"
|ptr[3]|------->|s[0]|--------->"black"
(**p)+1------------------->"ink"
#include <iostream>
using namespace std;
class animal
{
protected:
int age;
public:
virtual void print_age(void) = 0;
virtual void print_age1(void) = 0;
};
class dog:public animal
{
public:
dog(){this->age = 2;}
~dog(){}
virtual void print_age(void)
{
cout<<"wang.my age = "<<this->age<<endl;
}
virtual void print_age1(void)
{
cout<<"wang.my age1 = "<<this->age<<endl;
}
};
class cat : public animal
{
public:
cat(){this->age = 1;}
~cat(){}
virtual void print_age(void){cout<<"Miao,my age= "<<this->age<<endl;}
virtual void print_age1(void){cout<<"Miao,my age1= "<<this->age<<endl;}
};
int main()
{
cat kitty,kitty1,kitty2;
dog jd,jd1,jd2;
animal *pa;
int* p = (int*)(&kitty);
int* p1 = (int*)(&kitty1);
int* p2 = (int*)(&kitty2);
int* q = (int*)(&jd);
int* q1 = (int*)(&jd1);
int* q2 = (int*)(&jd2);
cout<<hex;
cout<<q[0]<<endl;
cout<<q1[0]<<endl;
cout<<q2[0]<<endl;
cout<<"-----------------"<<std::endl;
cout<<p2[0]<<endl;
cout<<p1[0]<<endl;
cout<<p[0]<<endl;
p[0] = q[0];
pa = &kitty;
pa->print_age();
pa->print_age1();
system("pause");
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/1$ ./5
2c44dce8
2c44dce8
2c44dce8
-----------------
2c44dcc8
2c44dcc8
2c44dcc8
wang.my age = 1
wang.my age1 = 1
sh: 1: pause: not found
xz@xiaqiu:~/study/cpp-primer/study/1$
#include <iostream>
using namespace std;
int i = 0;
int fun(int n)
{
static int a = 2;
a++;
return (a * n);
}
int main()
{
int k = 5;
{
int i = 2;
k += fun(i);
cout<<k<<endl;
}
k += fun(i);
cout<<k<<endl;
return (0);
}
xz@xiaqiu:~/study/cpp-primer/study/1$ ./6
11
11
xz@xiaqiu:~/study/cpp-primer/study/1$
#include <iostream>
using namespace std;
class B
{
public:
B(){cout<<"default constructor"<<endl;}
~B(){cout<<"destructed"<<endl;}
B(int i):data(i)
{cout<<"constructed by parameter "<<data<<endl;}
private:
int data;
};
B Play(B b){ return b; }
int main()
{
B temp = Play(5);
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/1$ ./7
constructed by parameter 5
destructed
destructed
xz@xiaqiu:~/study/cpp-primer/study/1$
#include <stdio.h>
#include <string.h>
class CBuffer
{
char *m_pBuffer;
int m_size;
public:
CBuffer(){ m_pBuffer = NULL;}
~CBuffer(){ Free(); }
void Allocte(int size) {
m_size = size;
m_pBuffer = new char[size];
}
private:
void Free()
{
if(m_pBuffer != NULL)
{
delete[] m_pBuffer;
m_pBuffer = NULL;
}
}
public:
void SaveString(const char* pText)
{
Allocte(sizeof(pText));
strcpy(m_pBuffer,pText);
}
char *GetBuffer() const
{
return m_pBuffer;
}
};
int main()
{
CBuffer buffer1;
buffer1.SaveString("Microsoft");
printf("%s\n", buffer1.GetBuffer());
}
xz@xiaqiu:~/study/cpp-primer/study/1$ ./8
Microsoft
xz@xiaqiu:~/study/cpp-primer/study/1$
#include <cstddef>
#include <string>
#include <iostream>
using namespace std;
inline string make_plural(size_t ctr, const string& word,
const string& ending)
{
return (ctr > 1) ? word + ending : word;
}
int main()
{
size_t cnt = 1;
cout<<make_plural(cnt,"success","es") << endl;
cnt = 2;
cout<<make_plural(cnt,"failure","s")<<endl;
return 0;
}
#include <iostream>
#include <string>
char &get_val(string &str, string::size_type ix)
{
return str[ix];
}
int main()
{
string s("a value");
cout<<s<<endl;
get_val(s,0) = 'A';
cout<<s<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
a value
A value
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
#include <string>
#include <vector>
#include <cstddef>
string::size_type find_char(const string& s,char c,string::size_type &occurs)
{
auto ret = s.size();
occurs = 0;
for(decltype(ret) i = 0; i != s.size(); ++i)
{
if(s[i] == c)
{
if(ret == s.size())
ret = i;
++occurs;
}
}
return ret;
}
vector<int>::const_iterator find_char(
vector<int>::const_iterator beg,
vector<int>::const_iterator end,
int value,
vector<int>::size_type &occurs
)
{
auto res_iter = end;
occurs = 0;
for(;beg != end;++beg)
{
if(*beg == value)
{
if(res_iter == end)
res_iter = beg;
++occurs;
}
}
return res_iter;
}
int main()
{
string s;
getline(cin,s);
size_t ctr = 0;
auto index = find_char(s,'o',ctr);
cout<<index<<" "<<ctr<<endl;
vector<int> ivec;
int i;
while(cin >> i)
ivec.push_back(i);
for(auto i : {42,33,92})
{
auto it = find_char(ivec.begin(),ivec.end(),i,ctr);
if(it == ivec.end())
cout<<i<<" is not in the input data"<<endl;
else
cout<<i<<" was at position "
<<it - ivec.begin()<<endl;
}
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
pooiiiidsao o oo o o oo
1 10
32 32 32 33 3 33 33 333 333 42 42 42 42 9 9 9 92 92 92
42 was at position 9
33 was at position 3
92 was at position 16
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
int &get(int *arry, int index){ return arry[index]; }
int main()
{
int ia[10];
for(int i = 0; i != 10; ++i)
{
get(ia,i) = i;
}
for(auto i : ia)
cout<<i<<" ";
cout<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
0 1 2 3 4 5 6 7 8 9
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
#include <vector>
using namespace std;
void reset(int &i)
{
i = 0;
}
void reset(int *ip)
{
*ip = 0;
ip = 0;
}
int main()
{
int j = 42;
reset(j);
cout<<"j = "<<j<<endl;
j = 42;
reset(&j);
cout<<"j = "<<j<<endl;
j = 42;
int *p = &j;
reset(p);
cout<<"j = "<<*p<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
j = 0
j = 0
j = 0
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
#include <iterator>
using namespace std;
void print(const char *cp)
{
if(cp)
while(*cp)
cout<<*cp++;
}
void print(const int *beg,const int *end)
{
while(beg != end)
cout<<*beg++<<" ";
}
int main()
{
print("hi world!");
cout<<endl;
int j[2] = {0,1};
print(begin(j),end(j));
cout<<endl;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
hi world!
0 1
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
#include <vector>
using namespace std;
int min_element(vector<int>::iterator,
vector<int>::iterator);
int (*pf)(vector<int>::iterator,vector<int>::iterator) = min_element;
int main()
{
vector<int> ivec{1,3,4,5,-1,32,-32};
cout<<"直接调用:"
<<min_element(ivec.begin(),ivec.end())<<endl;
cout<<"间接调用:"
<<pf(ivec.begin(),ivec.end())<<endl;
cout<<"等效的间接调用:"
<<(*pf)(ivec.begin(),ivec.end())<<endl;
return 0;
}
int min_element(vector<int>::iterator beg,
vector<int>::iterator end)
{
int minVal = 0;
while(beg != end)
{
if(minVal > *beg)
minVal = *beg;
++beg;
}
return minVal;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
直接调用:-32
间接调用:-32
等效的间接调用:-32
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <cstddef>
#include <cassert>
#include <string>
#include <iostream>
using namespace std;
void print(const int ia[], size_t size)
{
#ifndef NDEBUG
cerr<<__func__<<" : 数组大小是 "<<size<<endl;
#endif
}
int main()
{
string word = "foo";
const string::size_type threshold = 5;
if(word.size() < threshold)
cerr<<"错误: "<<__FILE__
<<" : 在函数中 "<<__func__
<<" 在行 "<<__LINE__<<endl
<<" at "<<__TIME__<<endl
<<"字读为 \""<<word
<<"\": 长度太短"<<endl;
word = "超过五个字符的长度";
assert(word.size() > threshold);
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
错误: /home/xz/study/cpp-primer/study/main1.cpp : 在函数中 main 在行 3264
at 21:24:24
字读为 "foo": 长度太短
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <string>
class Account
{
public:
Account() = default;
Account(const std::string &s,double amt):
owner(s),amount(amt){}
void calculate() { amount += amount * interestRate;}
double balance() { return amount; }
public:
static double rate() { return interestRate; }
static void rate(double);
private:
std::string owner;
double amount = 0.0;
static double interestRate;
static double initRate() { return .0225; }
static const std::string accountType;
static constexpr int period = 30;
double daily_tbl[period];
};
const string Account::accountType("Saving Account");
double Account::interestRate = initRate();
void Account::rate(double newRate)
{
interestRate = newRate;
}
#include <iostream>
using namespace std;
int main()
{
Sales_data data1,data2;
if(read(cin,data1) && read(cin,data2))
{
if(data1.isbn() == data2.isbn())
{
data1.combine(data2);
print(cout,data1);
cout<<endl;
}
}
else
cerr<<"Input failed!"<<endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
Sales_data total;
if(read(cin, total))
{
Sales_data trans;
while(read(cin,trans))
{
if(total.isbn() == trans.isbn())
{
total.combine(trans);
}
else
{
print(cout,total)<<endl;
total = trans;
}
}
print(cout,total)<<endl;
}
else
{
cerr << "No data?!" << endl;
}
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
1111 12 12
1111 2 12
1111 2 32
1112 3 12
1111 16 232 14.5
1112 23 12
1112 13 12
1112 39 468 12
xz@xiaqiu:~/study/cpp-primer/study/build$
class Debug
{
public:
constexpr Debug(bool b = true):hw(b),io(b),other(b){}
constexpr Debug(bool h,bool i,bool o):hw(h), io(i), other(o) { }
constexpr bool any() const { return hw || io || other;}
constexpr bool hardware(){ return hw || io;}
constexpr bool app(){ return other; }
void set_io(bool b){ io = b;}
void set_hw(bool b){ hw = b;}
void set_other(bool b){ hw = b; }
private:
bool hw;
bool io;
bool other;
};
class HW_Subsystem{
public:
HW_Subsystem():debug(false){}
bool field_debug() { return debug.any(); }
bool default_debug() const { return enable.any() && debug.any(); }
void set_debug(bool b){ debug.set_hw(b);}
private:
Debug debug;
constexpr static Debug enable{true,false,false};
};
class IO_Subsystem{
public:
IO_Subsystem():debug(false){}
bool field_debug() { return debug.any();}
bool default_debug() { return enable.any() && debug.any();}
void set_debug(bool b){ debug.set_io(b); }
private:
Debug debug;
constexpr static Debug enable{true,false,true};
};
#include <iostream>
using namespace std;
int main()
{
constexpr Debug io_sub(false,true,false);
if(io_sub.any())
cerr<<"打印适当的错误信息"<<endl;
constexpr Debug prod(false);
if(prod.any())
cerr<<"打印错误信息"<<endl;
IO_Subsystem ioErrs;
if(ioErrs.default_debug())
cerr<<"打印消息 3"<<endl;
ioErrs.set_debug(true);
if(ioErrs.default_debug())
cerr<<"打印消息 4"<<endl;
ioErrs.set_debug(false);
HW_Subsystem hw;
hw.set_debug(true);
if(ioErrs.default_debug() || hw.default_debug())
cerr<<"打印消息 5"<<endl;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
打印适当的错误信息
打印消息 4
打印消息 5
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <string>
#include <iostream>
class Screen
{
public:
typedef std::string::size_type pos;
Screen() = default;
Screen(pos ht,pos wd, char c): height(ht),width(wd),contents(ht * wd,c){}
friend class Window_mgr;
Screen(pos ht = 0,pos wd = 0):
cursor(0),height(ht),width(wd),contents(ht * wd, ' '){}
char get() const
{
return contents[cursor];
}
inline char get(pos ht, pos wd) const;
Screen &clear(char = bkground);
private:
static const char bkground = ' ';
public:
Screen &move(pos r, pos c);
Screen &set(char);
Screen &set(pos,pos,char);
Screen &display(std::ostream &os)
{
do_display(os);
return *this;
}
const Screen &display(std::ostream &os) const
{
do_display(os);
return *this;
}
private:
void do_display(std::ostream &os) const { os << contents; }
pos cursor = 0;
pos height = 0,width = 0;
std::string contents;
};
Screen &Screen::clear(char c)
{
contents = std::string(height * width,c);
return *this;
}
inline
Screen &Screen::move(pos r, pos c)
{
pos row = r * width;
cursor = row + c;
return *this;
}
char Screen::get(pos r, pos c) const
{
pos row = r * width;
return contents[row + c];
}
inline Screen &Screen::set(char c)
{
contents[cursor] = c;
return *this;
}
inline Screen &Screen::set(pos r, pos col, char ch)
{
contents[r*width + col] = ch;
return *this;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
Screen myScreen(5,3);
myScreen.move(4,0).set('#');
Screen nextScreen(5,5,'X');
nextScreen.move(4,0).set('#').display(cout);
cout<<"\n";
nextScreen.display(cout);
cout<<endl;
const Screen blank(5,3);
myScreen.set('#').display(cout);
cout<<endl;
blank.display(cout);
cout<<endl;
myScreen.clear('Z').display(cout); cout<<endl;
myScreen.move(4,0);
myScreen.set('#');
myScreen.display(cout);cout<<endl;
myScreen.clear('Z').display(cout); cout<<endl;
Screen temp = myScreen.move(4,0);
temp.set('#');
myScreen.display(cout);
cout<<endl;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
XXXXXXXXXXXXXXXXXXXX#XXXX
XXXXXXXXXXXXXXXXXXXX#XXXX
#
ZZZZZZZZZZZZZZZ
ZZZZZZZZZZZZ#ZZ
ZZZZZZZZZZZZZZZ
ZZZZZZZZZZZZZZZ
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
using namespace std;
int main()
{
cout<<"hi!"<<endl;
cout<<"hi!"<<flush;
cout<<"hi!"<<ends;
cout<<unitbuf;
cout<<"first"<<"second"<<endl;
cout<<nounitbuf;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
hi!
hi!hi!firstsecond
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
void read()
{
cin.setstate(cin.badbit | cin.eofbit | cin.failbit);
}
void off()
{
cin.clear(cin.rdstate() & ~cin.failbit & ~cin.badbit);
}
int main()
{
cout<<"before read"<<endl<<endl;
if(cin.good()) cout<<"cin's good"<<endl;
if(cin.bad()) cout<<"cin's bad"<<endl;
if(cin.fail()) cout<<"cin's fail"<<endl;
if(cin.eof()) cout<<"cin's eof"<<endl;
read();
cout<<"after read"<<endl<<endl;
if(cin.good()) cout<<"cin's good"<<endl;
if(cin.bad()) cout<<"cin's bad"<<endl;
if(cin.fail()) cout<<"cin's fail"<<endl;
if(cin.eof()) cout<<"cin's eof"<<endl;
off();
cout<<"after off"<<endl<<endl;
if (cin.good()) cout << "cin's good" << endl;
if (cin.bad()) cout << "cin's bad" << endl;
if (cin.fail()) cout << "cin's fail" << endl;
if (cin.eof()) cout << "cin's eof" << endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
before read
cin's good
after read
cin's bad
cin's fail
cin's eof
after off
cin's eof
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
#include <fstream>
#include <string>
#include <stdexcept>
using namespace std;
void process(ifstream &is)
{
string s;
while(is >> s)
cout<<s<<endl;
}
int main(int argc,char* argv[])
{
for(auto p = argv + 1; p != argv + argc;++p)
{
ifstream input(*p);
if(input)
{
process(input);
}
else
cerr<<"couldn't open: "<<string(*p);
}
auto p = argv + 1,end = argv + argc;
ifstream input;
while(p!=end)
{
input.open(*p);
if(input)
{
process(input);
}
else
cerr<<"couldn't open: "+string(*p);
input.close();
++p;
}
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test test1.txt test2.txt
test1.txt
test1.txt
test1.txt
test1.txt
test2.txt
test2.txt
test2.txt
test1.txt
test1.txt
test1.txt
test1.txt
test2.txt
test2.txt
test2.txt
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
struct PersonInfo
{
string name;
vector<string> phones;
};
string format(const string &s){ return s;}
bool valid(const string &s)
{
return true;
}
vector<PersonInfo> getData(istream &is)
{
string line,word;
vector<PersonInfo> people;
while(getline(is,line))
{
PersonInfo info;
istringstream record(line);
record >> info.name;
while(record >> word)
info.phones.push_back(word);
people.push_back(info);
}
return people;
}
ostream& process(ostream &os,vector<PersonInfo>people)
{
for(const auto &entry : people)
{
ostringstream formatted,badNums;
for(const auto &nums : entry.phones)
{
if(!valid(nums))
{
badNums<<" "<<nums;
}
else
formatted<<" "<<format(nums);
}
if(badNums.str().empty())
{
os<<entry.name<<" "
<<formatted.str()<<endl;
}
else
{
cerr<<"input error: "<<entry.name
<<" invalid number(s) "<<badNums.str()<<endl;
}
}
return os;
}
int main()
{
process(cout,getData(cin));
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
xiao 12345678
chen 123344567
123344 344556
wang 12233244
zhao 23345454
xiao 12345678
chen 123344567
123344 344556
wang 12233244
zhao 23345454
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int> ivec;
cout<<"ivec: size: "<<ivec.size()
<<" capacity: "<<ivec.capacity()<<endl;
for(vector<int>::size_type ix = 0; ix != 24;++ix)
ivec.push_back(ix);
cout<<"ivec: size: "<<ivec.size()
<<" capacity: "<<ivec.capacity()<<endl;
ivec.reserve(50);
cout<<"ivec: size: "<<ivec.size()
<<" capacity: "<<ivec.capacity()<<endl;
while(ivec.size() != ivec.capacity())
{
ivec.push_back(0);
}
cout<<"ivec: size: "<<ivec.size()
<<" capacity: "<<ivec.capacity()<<endl;
ivec.push_back(42);
cout<<"ivec: size: "<<ivec.size()
<<" capacity: "<<ivec.capacity()<<endl;
ivec.shrink_to_fit();
cout << "ivec: size: " << ivec.size()
<< " capacity: " << ivec.capacity() << endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
ivec: size: 0 capacity: 0
ivec: size: 24 capacity: 32
ivec: size: 24 capacity: 50
ivec: size: 50 capacity: 50
ivec: size: 51 capacity: 100
ivec: size: 51 capacity: 51
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <list>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
list<string> slist;
string s;
while(cin >> s)
slist.push_back(s);
auto iter = std::find(slist.begin(),slist.end(),"Quasimodo");
if(iter != slist.end())
slist.erase(iter);
auto orig = slist;
slist.clear();
cout<<"after clear,size is: "<<slist.size()<<endl;
slist = orig;
slist.erase(slist.begin(),slist.end());
cout<<"after erase begin to end, size is: "<<slist.size()<<endl;
slist = orig;
auto elem1 = slist.begin(),elem2 = slist.end();
elem1 = slist.erase(elem1,elem2);
cout<<"after erase elem1 to elem2 size is: "<<slist.size()<<endl;
if(elem1 != elem2)
cout<<"something wrong"<<endl;
else
cout<<"okay, they're equal "<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
aa aa aa cc cc ccc dd dd dd dd ss ss ss xx xx xx xx ccc cc cc cc ss sd dsa dsa dsa d xz xz xz cd fd wed sa dsa dsa dsd dsa sd fd dsa dsf rfgr grf gr g r gre gre ger g
after clear,size is: 0
after erase begin to end, size is: 0
after erase elem1 to elem2 size is: 0
okay, they're equal
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <algorithm>
#include <string>
#include <forward_list>
#include <vector>
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> lst = {0,1,2,3,4,5,6,7,8,9};
cout<<"initial list: ";
for(auto it : lst)
cout<<it<<" ";
cout<<endl;
auto it = lst.begin();
while(it != lst.end())
if(*it % 2)
it = lst.erase(it);
else
++it;
cout<<"从列表中删除奇数元素后:";
for(auto it : lst)
cout<<it<<" ";
cout<<endl;
forward_list<int> flst = {0,1,2,3,4,5,6,7,8,9};
cout<<"initial list:";
for(auto it : flst)
cout<<it<<" ";
cout<<endl;
auto prev = flst.before_begin();
auto curr = flst.begin();
while(curr != flst.end())
{
if(*curr % 2)
curr = flst.erase_after(prev);
else
{
prev = curr;
++curr;
}
}
cout<<"从 flst 擦除元素后:";
for(auto it : flst)
cout<<it<<" ";
cout<<endl;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
initial list: 0 1 2 3 4 5 6 7 8 9
从列表中删除奇数元素后:0 2 4 6 8
initial list:0 1 2 3 4 5 6 7 8 9
从 flst 擦除元素后:0 2 4 6 8
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name("AnnaBelle");
auto pos1 = name.find("Anna");
cout<<pos1<<" ";
string lowercase("annabelle");
pos1 = lowercase.find("Anna");
cout<<" "<<pos1<<" string::npos="<<string::npos<<endl;
return 0;
}
#include <string>
#include <iostream>
using namespace std;
int main()
{
string numbers("0123456789"),name("r2d2");
auto pos = name.find_first_of(numbers);
if(pos != string::npos)
{
cout<<"found number at index: " <<pos
<<" element is "<<name[pos]<<endl;
}
else
cout<<"no number in: "<<name<<endl;
pos = 0;
while((pos = name.find_first_of(numbers,pos)) !=
string::npos)
{
cout<<"found number at index: "<<pos
<<" element is "<<name[pos]<<endl;
++pos;
}
string river("Mississippi");
auto first_pos = river.find("is");
auto last_pos = river.rfind("is");
cout<<"find returned: "<<first_pos
<<" rfind returned: "<<last_pos<<endl;
string dept("03714p3");
pos = dept.find_first_not_of(numbers);
cout<<"first_not returned: "<<pos<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
found number at index: 1 element is 2
found number at index: 1 element is 2
found number at index: 3 element is 2
find returned: 1 rfind returned: 4
first_not returned: 5
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <vector>
#include <iostream>
using namespace std;
void printVec(const vector<int> &vi)
{
auto iter = vi.begin();
while(iter != vi.end())
cout<<*iter++<<" ";
cout<<endl;
}
int main()
{
vector<int> vi = {0,1,2,3,4,5,6,7,8,9};
printVec(vi);
auto iter = vi.begin();
while(iter != vi.end())
{
if(*iter % 2)
{
iter = vi.insert(iter,*iter);
iter += 2;
}
else
iter = vi.erase(iter);
}
printVec(vi);
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
0 1 2 3 4 5 6 7 8 9
1 1 3 3 5 5 7 7 9 9
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <cstddef>
#include <deque>
#include <stack>
#include <iostream>
using namespace std;
bool process(int);
int main()
{
stack<int> intStack;
for(size_t ix = 0; ix != 10; ++ix)
intStack.push(ix);
while(!intStack.empty())
{
int value = intStack.top();
cout<<value<<" ";
intStack.pop();
}
cout<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
9 8 7 6 5 4 3 2 1 0
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
string s = "some string",s2 = "some other string";
s.insert(s.begin(),s2.begin(),s2.end());
cout<<"insert iterators version: "<<s<<endl;
s = "some string";
s.insert(0,s2);
cout<<"insert string at given position: "<<s<<endl;
s = "some string";
s.insert(0,s2,0,s2.size());
cout<<"insert positional version: "<<s<<endl;
s = "";
vector<char> c_vec(1,'a');
s.insert(s.begin(),c_vec.begin(),c_vec.end());
s.insert(s.size(),5,'!');
cout<<s<<endl;
s.erase(s.size() - 5,5);
cout<<s<<endl;
s = "";
const char *cp = "Stately, plump Buck";
s.assign(cp,7);
cout<<s<<endl;
s.insert(s.size(), cp + 7);
cout<<s<<endl;
s = "C++ primer";
s2 = s;
s.insert(s.size(),"4th Ed ");
s2.append(" 4th Ed.");
cout<<s<<" "<<s2<<endl;
s.erase(11,3);
s.insert(11,"5th");
s2.replace(11,3,"5th");
cout<<s<<" "<<s2<<endl;
s.replace(11,3,"Fifth");
auto pos = s2.find("5th");
if(pos!=string::npos)
s2.replace(pos,3,"Fifth");
else
cout<<"something's wrong. s2 is: "<<s2<<endl;
cout<<s<<" "<<s2<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
insert iterators version: some other stringsome string
insert string at given position: some other stringsome string
insert positional version: some other stringsome string
a!!!!!
a
Stately
Stately, plump Buck
C++ primer4th Ed C++ primer 4th Ed.
C++ primer45thEd C++ primer 5th Ed.
C++ primer4FifthEd C++ primer Fifth Ed.
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <string>
#include <iostream>
#include <stdexcept>
using namespace std;
int main()
{
try
{
string s("hello world");
cout<<s.substr(0,5)<<endl;
cout<<s.substr(6)<<endl;
cout<<s.substr(6,11)<<endl;
cout<<s.substr(12)<<endl;
}
catch(out_of_range)
{
cout<<"caught out_of_range"<<endl;
}
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
hello
world
world
caught out_of_range
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
vector<int> vi;
int i;
while(cin>>i)
vi.push_back(i);
for_each(vi.begin(),vi.end(),[](int i){ cout<<i<<" ";});
cout<<endl;
vector<int> orig = vi;
std::transform(vi.begin(),vi.end(),vi.begin(),[](int i){return i < 0?-i:i;});
for_each(vi.begin(),vi.end(),[](int i){cout<<i<<" ";});
cout<<endl;
vi = orig;
transform(vi.begin(),vi.end(),vi.begin(),[](int i)->int{
if(i<0) return -i;else return i;
});
for_each(vi.begin(),vi.end(),[](int i){cout<<i<<" ";});
cout<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
-1 -12 -23 233232 3 232 32 32 13 21 -21 -434
-1 -12 -23 233232 3 232 32 32 13 21 -21 -434
1 12 23 233232 3 232 32 32 13 21 21 434
1 12 23 233232 3 232 32 32 13 21 21 434
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <iostream>
using namespace std;
int main()
{
vector<int> vec(10);
fill(vec.begin(),vec.end(),1);
int sum = accumulate(vec.begin(),vec.end(),0);
cout<<sum<<endl;
fill(vec.begin(),vec.begin() + vec.size()/2,10);
cout<<accumulate(vec.begin(), vec.end(),0)<<endl;
fill_n(vec.begin(),vec.size()/2,0);
cout<<accumulate(vec.begin(),vec.end(), 0)<<endl;
fill_n(back_inserter(vec),10,42);
cout<<accumulate(vec.begin(),vec.end(),0)<<endl;
vector<string> v;
string s;
while(cin>>s)
v.push_back(s);
string concat = accumulate(v.cbegin(),v.cend(),string(" "));
cout<<concat<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
10
55
5
425
hello world
xiao
helloworldxiao
xz@xiaqiu:~/study/cpp-primer/study/build$
#include <numeric>
#include <iterator>
#include <iostream>
using namespace std;
int main()
{
istream_iterator<int> in(cin),eof;
cout<<accumulate(in,eof,0)<<endl;
return 0;
}
xz@xiaqiu:~/study/cpp-primer/study/build$ ./test
1 2 23 4 5
35
xz@xiaqiu:~/study/cpp-primer/study/build$
#endif