#if 0//17.1 write.cpp 2021年03月16日 星期二 19时05分03秒
#include
#include
int main(){
const char * state1 = “Florida”;
const char * state2 = “Kansas”;
const char * state3 = “Euphoria”;
int len = std::strlen(state2);
std::cout << “Increasing loop index:\n”;
int i;
for(i = 1; i <= len; i++){
std::cout.write(state2, i);
std::cout << std::endl;
}
std::cout << “Decreasing loop index:\n”;
for(i = len; i > 0; i–)
std::cout.write(state2, i) << std::endl;
std::cout << “Exceeding string length:\n”;
std::cout.write(state2, len + 5) << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
Increasing loop index:
K
Ka
Kan
Kans
Kansa
Kansas
Decreasing loop index:
Kansas
Kansa
Kans
Kan
Ka
K
Exceeding string length:
KansasEuph
#endif
#if 0//17.2 defaults.cpp 2021年03月16日 星期二 19时10分12秒
#include
int main(){
std::cout << “12345678901234567890\n”;
char ch = ‘K’;
int t = 273;
std::cout << ch << “:\n”;
std::cout << t << “:\n”;
std::cout << -t << “:\n”;
double f1 = 1.200;
std::cout << f1 << “:\n”;
std::cout << (f1 + 1.0/9.0) << “:\n”;
double f2 = 1.67E2;
std::cout << f2 << ":\n";
f2 += 1.0/9.0;
std::cout << f2 << ":\n";
std::cout << (f2 * 1.0e4) << ":\n";
double f3 = 2.3e-4;
std::cout << f3 << ":\n";
std::cout << f3 / 10 << ":\n";
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
12345678901234567890
K:
273:
-273:
1.2:
1.31111:
167:
167.111:
1.67111e+06:
0.00023:
2.3e-05:
#endif
#if 0//17.3 manip.cpp 2021年03月16日 星期二 19时15分01秒
#include
int main(){
std::cout << "Enter an integer: “;
int n;
std::cin >> n;
std::cout << “n n*n\n”;
std::cout << n << " " << n * n << " (decimal)\n”;
std::cout << std::hex;
std::cout << n << " “;
std::cout << n * n << " (hexadecimal)\n”;
std::cout << std::oct << n << " " << n * n << " (octal)\n";
dec(std::cout);
std::cout << n << " " << n * n << " (decimal)\n";
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
Enter an integer: 13
n n*n
13 169 (decimal)
d a9 (hexadecimal)
15 251 (octal)
13 169 (decimal)
#endif
#if 0// 17.4 width.cpp 2021年03月16日 星期二 19时19分54秒
#include
int main(){
int w = std::cout.width(30);
std::cout << "default field width = "<< w << “:\n”;
std::cout.width(5);
std::cout << “N” << ‘:’;
std::cout.width(8);
std::cout << “N * N” << “:\n”;
for(long i = 1; i <= 100; i *= 10){
std::cout.width(5);
std::cout << i << ‘:’;
std::cout.width(8);
std::cout << i * i << “:\n”;
}
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
default field width = 0:
N: N * N:
1: 1:
10: 100:
100: 10000:
#endif
#if 0 //17.5 fill.cpp 2021年03月16日 星期二 19时23分43秒
#include
int main(){
std::cout.fill(’*’);
const char * staff[2] { “Waldo Whipsnade”, “Wilmarie Wooper”};
long bonus[2] {900, 1350};
for(int i = 0; i < 2; i++){
std::cout << staff[i] << ": KaTeX parse error: Undefined control sequence: \n at position 55: …< bonus[i] << "\̲n̲"; } return … ./hello
Waldo Whipsnade: $****900
Wilmarie Wooper: $***1350
#endif
#if 0//17.6 precise.cpp 2021年03月16日 星期二 19时26分54秒
#include
int main(){
float price1 = 20.40;
float price2 = 1.9 + 8.0/9.0;
std::cout << "“Furry Friends” is KaTeX parse error: Undefined control sequence: \n at position 18: …<< price1 << "!\̲n̲"; std::cout <…" << price2 << “!\n”;
std::cout.precision(2);
std::cout << "\"Furry Friends\" is $" << price1 << "!\n";
std::cout << "\"Fiery Fiends\" is $" << price2 << "!\n";
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
“Furry Friends” is $20.4!
“Fiery Fiends” is $2.78889!
“Furry Friends” is $20!
“Fiery Fiends” is $2.8!
#endif
#if 0//17.7 showpt.cpp 2021年03月16日 星期二 19时31分18秒
#include
int main(){
float price1 = 20.40;
float price2 = 1.9 + 8.0/9.0;
std::cout.setf(std::ios_base::showpoint);
std::cout << "“Furry Friends” is KaTeX parse error: Undefined control sequence: \n at position 18: …<< price1 << "!\̲n̲"; std::cout <…" << price2 << “!\n”;
std::cout.precision(2);
std::cout << "\"Furry Friends\" is $" << price1 << "!\n";
std::cout << "\"Fiery Fiends\" is $" << price2 << "!\n";
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
“Furry Friends” is $20.4000!
“Fiery Fiends” is $2.78889!
“Furry Friends” is $20.!
“Fiery Fiends” is $2.8!
#endif
#if 0//17.8 setf.cpp 2021年03月16日 星期二 19时34分35秒
#include
int main(){
int temperature = 63;
std::cout << "Today’s water temperature: ";
std::cout.setf(std::ios_base::showpos);
std::cout << temperature << std::endl;
std::cout << "For our programming friends, that's\n";
std::cout << std::hex << temperature << std::endl;
std::cout.setf(std::ios_base::uppercase);
std::cout.setf(std::ios_base::showbase);
std::cout << "or\n";
std::cout << temperature << std::endl;
std::cout << "How " << true << "! oops --How ";
std::cout.setf(std::ios_base::boolalpha);
std::cout << true << "!\n";
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
Today’s water temperature: +63
For our programming friends, that’s
3f
or
0X3F
How 0X1! oops --How true!
#endif
#if 0//17.9 setf2.cpp 2021年03月16日 星期二 19时39分54秒
#include
#include
int main(){
std::cout.setf(std::ios_base::left, std::ios_base::adjustfield);
std::cout.setf(std::ios_base::showpos);
std::cout.setf(std::ios_base::showpoint);
std::cout.precision(3);
std::ios_base::fmtflags old = std::cout.setf(std::ios_base::scientific,
std::ios_base::floatfield);
std::cout << “Left Justification:\n”;
long n;
for(n = 1; n <= 41; n += 10){
std::cout.width(4);
std::cout << n << “|”;
std::cout.width(12);
std::cout << sqrt(double (n)) << “|\n”;
}
std::cout.setf(std::ios_base::internal, std::ios_base::adjustfield);
std::cout.setf(old, std::ios_base::floatfield);
std::cout << "Internal Justification:\n";
for(n = 1; n <= 41; n += 10){
std::cout.width(4);
std::cout << n << "|";
std::cout.width(12);
std::cout << sqrt(double (n)) << "|\n";
}
std::cout.setf(std::ios_base::right, std::ios_base::adjustfield);
std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
std::cout << "Right Justification:\n";
for(n = 1; n <= 41; n += 10){
std::cout.width(4);
std::cout << n << "|";
std::cout.width(12);
std::cout << sqrt(double (n)) << "|\n";
}
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
Left Justification:
+1 |+1.000e+00 |
+11 |+3.317e+00 |
+21 |+4.583e+00 |
+31 |+5.568e+00 |
+41 |+6.403e+00 |
Internal Justification:
#endif
#if 0//17.10 iomanip.cpp 2021年03月16日 星期二 19时48分39秒
#include
#include
#include
int main(){
std::cout << std::fixed << std::right;
std::cout << std::setw(6) << “N” << std::setw(14) << “square root”
<< std::setw(15) << “fourth root\n”;
double root;
for(int n = 10; n <= 100; n += 10){
root = sqrt(double(n));
std::cout << std::setw(6) << std::setfill(’.’) << n << std::setfill(’ ')
<< std::setw(12) << std::setprecision(3) << root
<< std::setw(14) << std::setprecision(4) << sqrt(root)
<< std::endl;
}
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
N square root fourth root
…10 3.162 1.7783
…20 4.472 2.1147
…30 5.477 2.3403
…40 6.325 2.5149
…50 7.071 2.6591
…60 7.746 2.7832
…70 8.367 2.8925
…80 8.944 2.9907
…90 9.487 3.0801
…100 10.000 3.1623
#endif
#if 0//17.11 check_it.cpp 2021年03月17日 星期三 19时03分00秒
#include
int main(){
std::cout << "Enter numbers: ";
int sum = 0;
int input;
while(std::cin >> input){
sum += input;
}
std::cout << "Last value entered = " << input << std::endl;
std::cout << "Sum = " << sum << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
Enter numbers: 200
10 -50 -123z 60
Last value entered = 0
Sum = 37
#endif
#if 0//17.12 cinexcp.cpp 2021年03月17日 星期三 19时06分29秒
#include
#include
int main(){
std::cin.exceptions(std::ios_base::failbit);
std::cout << "Enter numbers: ";
int sum = 0;
int input;
try{
while(std::cin >> input){
sum += input;
}
}catch(std::ios_base::failure & bf){
std::cout << bf.what() << std::endl;
std::cout << “O! the horror!\n”;
}
std::cout << "Last value entered = " << input << std::endl;
std::cout << "Sum = " << sum << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
Enter numbers: 20 30 40 pi 6
basic_ios::clear: iostream error
O! the horror!
Last value entered = 0
Sum = 90
#endif
#if 0//17.13 get_gun.cpp 2021年03月17日 星期三 19时11分31秒
#include
const int Limit = 255;
int main(){
char input[Limit];
std::cout << “Enter a string for getline() processing:\n”;
std::cin.getline(input, Limit, ‘#’);
std::cout << “Here is your input:\n”;
std::cout << input << “\nDone with phase 1\n”;
char ch;
std::cin.get(ch);
std::cout << "The next input character is " << ch << std::endl;
if(ch != '\n')
std::cin.ignore(Limit, '\n');
std::cout << "Enter a string for get() processing:\n";
std::cin.get(input, Limit, '#');
std::cout << "Here is your input:\n";
std::cout << input << "\nDone with phase 2\n";
std::cin.get(ch);
std::cout << "The next input character is " << ch << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
Enter a string for getline() processing:
Please pass
me a #3 melon!
Here is your input:
Please pass
me a
Done with phase 1
The next input character is 3
Enter a string for get() processing:
I still
want my #3 melon!
Here is your input:
I still
want my
Done with phase 2
The next input character is #
#endif
#if 0//17.14 peeker.cpp 2021年03月17日 星期三 19时17分42秒
#include
int main(){
char ch;
while(std::cin.get(ch)){
if(ch != ‘#’)
std::cout << ch;
else{
std::cin.putback(ch);
break;
}
}
if(!std::cin.eof()){
std::cin.get(ch);
std::cout << std::endl << ch << " is next input character.\n";
}else{
std::cout << “End of file reached.\n”;
std::exit(0);
}
while(std::cin.peek() != '#'){
std::cin.get(ch);
std::cout << ch;
}
if(!std::cin.eof()){
std::cin.get(ch);
std::cout << std::endl << ch << " is next input character.\n";
}else
std::cout << "End of file reached.\n";
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
I used a #3 pencil when I should have used a #2.
I used a
3 pencil when I should have used a
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
I used a #3 pencil when I should have used a #2.
I used a
3 pencil when I should have used a
#endif
#if 0// 17.15 truncate.cpp 2021年03月17日 星期三 19时23分38秒
#include
const int SLEN = 10;
inline void eatline() { while (std::cin.get() != ‘\n’) continue; }
int main(){
char name[SLEN];
char title[SLEN];
std::cout << "Enter your name: ";
std::cin.get(name, SLEN);
if(std::cin.peek() != ‘\n’)
std::cout << "Sorry, we only have enough room for "
<< name << std::endl;
eatline();
std::cout << “Dear " << name << “, enter your title: \n”;
std::cin.get(title, SLEN);
if(std::cin.peek() != ‘\n’)
std::cout << " We were forcedd to truncate your title.\n”;
eatline();
std::cout << " Name: " << name << "\nTitle: " << title << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
Enter your name: Ella Fishsniffer
Sorry, we only have enough room for Ella Fis
Dear Ella Fis, enter your title:
Excutive Adjunct
We were forcedd to truncate your title.
Name: Ella Fis
Title: Excutive
#endif
#if 0// 17.16 fileio.cpp 2021年03月17日 星期三 19时30分42秒
#include
#include
#include
int main(){
std::string filename;
std::cout << "Enter name for new file: ";
std::cin >> filename;
std::ofstream fout(filename.c_str());
fout << “For your eyes only!\n”;
std::cout << "Enter your secret number: ";
float secret;
std::cin >> secret;
fout << "Your secret number is " << secret << std::endl;
fout.close();
std::ifstream fin(filename.c_str());
std::cout << "Here are the contents of " << filename << ":\n";
char ch;
while(fin.get(ch))
std::cout << ch;
std::cout << "Done\n";
fin.close();
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
Enter name for new file: pythag
Enter your secret number: 3.14159
Here are the contents of pythag:
For your eyes only!
Your secret number is 3.14159
Done
#endif
#if 0//17.17 count.cpp 2021年03月17日 星期三 19时38分28秒
#include
#include
#include
int main(int argc, char * argv[]){
if(argc == 1){
std::cerr << “Usage: " << argv[0] << " filename[s]\n”;
exit(EXIT_FAILURE);
}
std::ifstream fin;
long count;
long total = 0;
char ch;
for(int file = 1; file < argc; file++){
fin.open(argv[file]);
if(!fin.is_open()){
std::cerr << “Could not open " << argv[file] << std::endl;
fin.clear();
continue;
}
count = 0;
while(fin.get(ch))
count++;
std::cout << count << " characters in " << argv[file] << std::endl;
total += count;
fin.clear();
fin.close();
}
std::cout << total << " characters in all files\n”;
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello paris rome
Could not open paris
Could not open rome
0 characters in all files
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
Usage: ./hello filename[s]
#endif
#if 0// 17.18 append.cpp 2021年03月17日 星期三 19时48分13秒
#include
#include
#include
#include
const char * file = “guest.txt”;
int main(){
char ch;
std::ifstream fin;
fin.open(file);
if(fin.is_open()){
std::cout << “Here are the current contents of the "
<< file << " file:\n”;
while(fin.get(ch))
std::cout << ch;
fin.close();
}
std::ofstream fout(file, std::ios::out | std::ios::app);
if(!fout.is_open()){
std::cerr << "Can't open " << file << " file for output.\n";
exit(EXIT_FAILURE);
}
std::cout << "Enter guest names(enter a blank line to quit):\n";
std::string name;
while(getline(std::cin, name) && name.size() > 0){
fout << name << std::endl;
}
fout.close();
fin.clear();
fin.open(file);
if(fin.is_open()){
std::cout << "Here are the new contents of the "
<< file << " file:\n ";
while(fin.get(ch))
std::cout << ch;
fin.close();
}
std::cout << "Done.\n";
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
Enter guest names(enter a blank line to quit):
Genghis Kant
Hank Attila
Charles Bigg
^Z
[2]+ 已停止 ./hello
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
Here are the current contents of the guest.txt file:
Genghis Kant
Hank Attila
Charles Bigg
Enter guest names(enter a blank line to quit):
Greta Greppo
LaDonna Mobile
Fannie Mae
q
[3]+ 已停止 ./hello
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
Here are the current contents of the guest.txt file:
Genghis Kant
Hank Attila
Charles Bigg
Greta Greppo
LaDonna Mobile
Fannie Mae
q
Enter guest names(enter a blank line to quit):
#endif
#if 0//17.19 binary.cpp 2021年03月18日 星期四 19时12分17秒
#include
#include
#include
#include
inline void eatline(){ while (std::cin.get() != ‘\n’) continue;}
struct planet{
char name[20];
double population;
double g;
};
const char * file = “planets.dat”;
int main(){
planet p1;
std::cout << std::fixed << std::right;
std::ifstream fin;
fin.open(file, std::ios_base::in | std::ios_base::binary);
if(fin.is_open()){
std::cout << "Here are the current contents of the "
<< file << " file:\n";
while (fin.read((char *)&p1, sizeof p1)){
std::cout << std::setw(20) << p1.name<< ": "
<< std::setprecision(0) << std::setw(12) << p1.population
<< std::setprecision(2) << std::setw(6) << p1.g << std::endl;
}
fin.close();
}
std::ofstream fout (file, std::ios_base::out | std::ios_base::app |
std::ios_base::binary);
if(!fout.is_open()){
std::cerr << "Can't open " << file << " file for output:\n";
exit(EXIT_FAILURE);
}
std::cout << "Enter planet name(enter a blank line to quit):\n";
std::cin.get(p1.name, 20);
while(p1.name[0] != '\0'){
eatline();
std::cout << "Enter planetary population: ";
std::cin >> p1.population;
std::cout << "Enter planet's acceleration of gravity: ";
std::cin >> p1.g;
eatline();
fout.write((char *) &p1, sizeof p1);
std::cout << "Enter planet name(enter a blank line "
"to quit):\n";
std::cin.get(p1.name, 20);
}
fout.close();
fin.clear();
fin.open(file, std::ios_base::in | std::ios_base::binary);
if(fin.is_open()){
std::cout << "Here are the new contents of the "
<< file << " file:\n";
while(fin.read((char *) & p1, sizeof p1)){
std::cout << std::setw(20) << p1.name << ": "
<< std::setprecision(0) << std::setw(12) << p1.population
<< std::setprecision(2) << std::setw(6) << p1.g << std::endl;
}
fin.close();
}
std::cout << "Done.\n";
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
Enter planet name(enter a blank line to quit):
Earth
Enter planetary population: 6928198253
Enter planet’s acceleration of gravity: 9.81
Enter planet name(enter a blank line to quit):
Here are the new contents of the planets.dat file:
Earth: 6928198253 9.81
Done.
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
Here are the current contents of the planets.dat file:
Earth: 6928198253 9.81
Enter planet name(enter a blank line to quit):
Jenny’s World
Enter planetary population: 32155648
Enter planet’s acceleration of gravity: 8.93
Enter planet name(enter a blank line to quit):
Here are the new contents of the planets.dat file:
Earth: 6928198253 9.81
Jenny’s World: 32155648 8.93
Done.
#endif
#if 0//17.20 random.cpp 2021年03月18日 星期四 19时34分10秒
#include
#include
#include
#include
const int LIM = 20;
struct planet{
char name[LIM];
double population;
double g;
};
const char * file = “planets.dat”;
inline void eatline() { while (std::cin.get() != ‘\n’) continue; }
int main(){
planet p1;
std::cout << std::fixed ;
std::fstream finout;
//std::ifstream 打错了!!!
finout.open(file, std::ios_base::in | std::ios_base::binary);
int ct = 0;
if(finout.is_open()){
finout.seekg(0);
std::cout << "Here are the current contents of the "
<< file << " file:\n";
while (finout.read((char *)&p1, sizeof p1)){
std::cout << ct++ << std::setw(LIM) << p1.name<< ": "
<< std::setprecision(0) << std::setw(12) << p1.population
<< std::setprecision(2) << std::setw(6) << p1.g << std::endl;
}
if(finout.eof())
finout.clear();
else{
std::cerr << "Error in reading " << file << ".\n";
exit(EXIT_FAILURE);
}
}
else{
std::cerr << file << " could not be opened --bye.\n";
exit(EXIT_FAILURE);
}
std::cout << "Enter the record number you wish to change: ";
long rec;
std::cin >> rec;
eatline();
if(rec < 0 || rec >= ct){
std::cerr << " Invalid recode number --bye.\n";
exit(EXIT_FAILURE);
}
std::streampos place = rec * sizeof p1;
finout.seekg(place);
if(finout.fail()){
std::cerr << "Error on attempted seek\n";
exit(EXIT_FAILURE);
}
finout.read((char *)&p1, sizeof p1);
std::cout << "Yout selection:\n";
std::cout << rec << ": " << std::setw(LIM) << p1.name<< ": "
<< std::setprecision(0) << std::setw(12) << p1.population
<< std::setprecision(2) << std::setw(6) << p1.g << std::endl;
if(finout.eof())
finout.clear();
std::cout << "Enter planet name: ";
std::cin.get(p1.name, LIM);
eatline();
std::cout << "Enter planetary population: ";
std::cin >> p1.population;
std::cout << "Enter planet's acceleration of gravity: ";
std::cin >> p1.g;
finout.seekg(place);
finout.write((char *) &p1, sizeof p1) << std::flush;
if(finout.fail()){
std::cerr << "Error on attempted write\n";
exit(EXIT_FAILURE);
}
ct = 0;
finout.seekg(0);
std::cout << "Here are the new contents of the " << file <<
" file:\n";
while (finout.read((char *)&p1, sizeof p1)){
std::cout << ct++ << std::setw(LIM) << p1.name<< ": "
<< std::setprecision(0) << std::setw(12) << p1.population
<< std::setprecision(2) << std::setw(6) << p1.g << std::endl;
}
finout.close();
std::cout << "Done.\n";
return 0;
}
#endif
#if 0//17.21 strout.cpp 2021年03月19日 星期五 19时02分45秒
#include
#include
#include
int main(){
std::ostringstream outstr;
std::string hdisk;
std::cout << "What’s the name of your hard disk? ";
getline(std::cin, hdisk);
int cap;
std::cout << "What’s its capacity in GB? ";
std::cin >> cap;
outstr << “The hard disk " << hdisk << " has a capacity of "
<< cap << " gigabytes.\n”;
std::string result = outstr.str();
std::cout << result;
return 0;
}
g++ prog.cc -Wall -Wextra -I/opt/wandbox/boost-1.73.0/gcc-head/include -std=gnu++2b
Start
What’s the name of your hard disk? What’s its capacity in GB? The hard disk has a capacity of 0 gigabytes.
0
Finish
#endif
#if 0//17.22 strin.cpp 2021年03月19日 星期五 19时10分49秒
#include
#include
#include
int main(){
std::string lit = "It was a dark and stormy day, and "
" the full moon glowed brilliantly. ";
std::istringstream instr(lit);
std::string word;
while (instr >> word)
std::cout << word << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/c++Primer Plus$ ./hello
It
was
a
dark
and
stormy
day,
and
the
full
moon
glowed
brilliantly.
#endif
//The C++ Standard Library 2nd
#if 0 // util/pair1.cpp 2021年03月19日 星期五 19时28分53秒 p64
#include
#include
#include
class Foo {
public:
Foo(std::tuple
std::cout << “Foo::Foo(tuple)” << std::endl;
}
template
Foo (Args…args){
std::cout << “Foo::Foo(args…)” << std::endl;
}
};
int main(){
std::tuple
std::pair
std::pair
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
Foo::Foo(tuple)
Foo::Foo(args…)
#endif
#if 0 //util/tuple1.cpp 2021年03月19日 星期五 19时35分24秒 p68
#include
#include
#include
#include
int main(){
std::tuple
std::tuple
std::cout << std::get<0>(t1) << " ";
std::cout << std::get<1>(t1) << " ";
std::cout << std::get<2>(t1) << " ";
std::cout << std::endl;
auto t2 = std::make_tuple(22, 44, "nico");
std::get<1>(t1) = std::get<1>(t2);
if(t1 < t2){
t1 = t2;
}
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
41 6.3 nico
#endif
#if 0//util/tuple2.cpp 2021年03月19日 星期五 19时41分53秒
#include “printtuple.hpp”
#include
#include
#include
int main(){
std::tuple
std::cout << "io: " << t << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
io: [77,1.1,more light]
#endif
#if 0//util/sharedptr1.cpp p78 2021年03月19日 星期五 20时02分26秒
#include
#include
#include
#include
int main(){
std::shared_ptrstd::stringpNico(new std::string(“nico”));
std::shared_ptrstd::stringpJutta(new std::string(“jutta”));
(*pNico)[0] = ‘N’;
pJutta->replace(0, 1, “J”);
std::vector> whoMadeCoffee;
whoMadeCoffee.push_back(pJutta);
whoMadeCoffee.push_back(pJutta);
whoMadeCoffee.push_back(pNico);
whoMadeCoffee.push_back(pJutta);
whoMadeCoffee.push_back(pNico);
for(auto ptr: whoMadeCoffee){
std::cout << *ptr << " ";
}
std::cout << std::endl;
*pNico = "Nicolai";
for(auto ptr: whoMadeCoffee){
std::cout << *ptr << " ";
}
std::cout << std::endl;
std::cout << "use_count: " << whoMadeCoffee[0].use_count() << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
Jutta Jutta Nico Jutta Nico
Jutta Jutta Nicolai Jutta Nicolai
use_count: 4
#endif
#if 0//util/sharedptr2.cpp 2021年03月20日 星期六 21时22分27秒
#include
#include
#include
#include
#include
class FileDeleter{
private:
std::string filename;
public:
FileDeleter (const std::string& fn)
: filename(fn){
}
void operator()(std::ofstream* fp){
fp->close();
std::remove(filename.c_str());
}
};
int main(){
std::shared_ptrstd::ofstream fp(new std::ofstream(“tmpfile.txt”),
FileDeleter(“tmpfile.txt”));
return 0;
}
#endif
#if 1//util/sharedptr3.cpp 2021年03月20日 星期六 21时28分08秒
#include
#include
#include
#include
#include
#include
#include
#include
class SharedMemoryDetacher{
public:
void operator()(int * p){
std::cout << “unlink /tmp1234” << std::endl;
if(shm_unlink("/tmp1234") != 0){
std::cerr << “OOPS: shm_unlink() failed” << std::endl;
}
}
};
std::shared_ptr getSharedIntMemory(int num){
void * mem;
int shmfd = shm_open("/tmp1234", O_CREAT|O_RDWR, S_IRWXU|S_IRWXG);
if(shmfd < 0){
throw std::string(strerror(errno));
}
if(ftruncate(shmfd, num * sizeof(int)) == -1){
throw std::string(strerror(errno));
}
mem = mmap(nullptr, num * sizeof(int), PROT_READ | PROT_WRITE,
MAP_SHARED, shmfd, 0);
if(mem == MAP_FAILED){
throw std::string(strerror(errno));
}
return std::shared_ptr(static_cast
SharedMemoryDetacher());
}
int main(){
std::shared_ptr smp(getSharedIntMemory(100));
for(int i = 0; i < 100; ++i){
smp.get()[i] = i * 42;
}
std::cout << “” << std::endl;
std::cin.get();
smp.reset();
return 0;
}
对‘shm_open’未定义的引用
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ g++ hello.cpp -o hello -lrt
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
1234
unlink /tmp1234
#endif
#if 0//util/weakptr1.cpp 2021年03月21日 星期日 07时20分18秒
#include
#include
#include
#include
class Person{
public:
std::string name;
std::shared_ptr mother;
std::shared_ptr father;
std::vector
Person(const std::string & n,
std::shared_ptr m = nullptr,
std::shared_ptr f = nullptr)
:name(n), mother(m), father(f){
}
~Person(){
std::cout << "delete " << name << std::endl;
}
};
std::shared_ptr initFamily(const std::string& name){
std::shared_ptr mom (new Person(name + “'s mom”));
std::shared_ptr dad (new Person(name + “'s dad”));
std::shared_ptr kid(new Person(name, mom, dad));
mom->kids.push_back(kid);
dad->kids.push_back(kid);
return kid;
}
int main(){
std::shared_ptr p = initFamily(“nico”);
std::cout <<“nico’s family exists” << std::endl;
std::cout << “-nico is shared " << p.use_count() << " times” << std::endl;
std::cout << "-name of 1st kid of nico’s mom: "
<< p->mother->kids[0]->name << std::endl;
p = initFamily(“jim”);
std::cout << “jim’s family exists” << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
nico’s family exists
-nico is shared 3 times
-name of 1st kid of nico’s mom: nico
jim’s family exists
#endif
#if 0//util/weakptr2.cpp 2021年03月21日 星期日 07时20分18秒
#include
#include
#include
#include
class Person{
public:
std::string name;
std::shared_ptr mother;
std::shared_ptr father;
std::vector
//std::vector
/*hello.cpp:288:24: 错误:‘->’的基操作数具有非指针类型‘__gnu_cxx::__alloc_traits
288 | << p->mother->kids[0]->name << std::endl;
*/
Person(const std::string & n,
std::shared_ptr m = nullptr,
std::shared_ptr f = nullptr)
:name(n), mother(m), father(f){
}
~Person(){
std::cout << "delete " << name << std::endl;
}
};
std::shared_ptr initFamily(const std::string& name){
std::shared_ptr mom (new Person(name + “'s mom”));
std::shared_ptr dad (new Person(name + “'s dad”));
std::shared_ptr kid(new Person(name, mom, dad));
mom->kids.push_back(kid);
dad->kids.push_back(kid);
return kid;
}
int main(){
std::shared_ptr p = initFamily(“nico”);
std::cout <<“nico’s family exists” << std::endl;
std::cout << “-nico is shared " << p.use_count() << " times” << std::endl;
std::cout << "-name of 1st kid of nico’s mom: "
<< p->mother->kids[0]->name << std::endl;
p = initFamily(“jim”);
std::cout << “jim’s family exists” << std::endl;
return 0;
}
#endif
#if 0//util/uniqueptr1.cpp 2021年03月21日 星期日 07时41分17秒 p108
#include
#include
#include
#include
#include
#include
class DirCloser{
public:
void operator()(DIR * dp){
if(closedir(dp) != 0){
std::cerr << “OOPS: closedir() failed” << std::endl;
}
}
};
int main(){
std::unique_ptr
#endif
#if 0//util/limits1.cpp 2021年03月21日 星期日 07时51分02秒
#include
#include
#include
int main(){
std::cout << std::boolalpha;
std::cout << "max(short): "<< std::numeric_limits::max() << std::endl;
std::cout << "max(int): " << std::numeric_limits::max() << std::endl;
std::cout << "max(long): " << std::numeric_limits::max() << std::endl;
std::cout << std::endl;
std::cout << "max(float): "
<< std::numeric_limits::max() << std::endl;
std::cout << "max(int): "
<< std::numeric_limits::max() << std::endl;
std::cout << "max(long): "
<< std::numeric_limits::max() << std::endl;
std::cout << std::endl;
std::cout << "is_signed(char): "
<< std::numeric_limits::is_signed << std::endl;
std::cout << std::endl;
std::cout << "is_specialized(string): "
<< std::numeric_limitsstd::string::is_specialized << std::endl;
// 打错了 <
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
max(short): 32767
max(int): 2147483647
max(long): 9223372036854775807
max(float): 3.40282e+38
max(int): 2147483647
max(long): 9223372036854775807
is_signed(char): true
is_specialized(string): false
#endif
#if 0 //util/minmax1.cpp 2021年03月21日 星期日 08时03分50秒
#include
#include
bool int_ptr_less(int* a, int* b){
return * a < * b;
}
int main(){
int x = 17;
int y = 42;
int z = 33;
int* px = &x;
int* py = &y;
int* pz = &z;
int* pmax = std::max(px, py, int_ptr_less);
std::pair extremes = std::minmax({px, py, pz}, int_ptr_less);
return 0;
}
#endif
#if 0//util/ratio1.cpp 2021年03月21日 星期日 15时59分22秒
#include
#include
int main(){
typedef std::ratio<5, 3> FiveThirds;
std::cout << FiveThirds::num << “/” << FiveThirds::den << std::endl;
typedef std::ratio<25, 15> AlsoFiveThirds;
std::cout << AlsoFiveThirds::num << “/” << AlsoFiveThirds::den << std::endl;
std::ratio<42, 42> one;
std::cout << one.num << “/” << one.den << std::endl;
std::ratio<0> zero;
std::cout << zero.num << "/" << zero.den << std::endl;
typedef std::ratio<7, -3>Neg;
std::cout << Neg::num << "/" << Neg::den << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
5/3
5/3
1/1
0/1
-7/3
#endif
#if 0//tuil/clock.hpp
#include
#include “clock.hpp”
int main(){
std::cout << "system_clock: " << std::endl;
printClockDatastd::chrono::system_clock();
std::cout << "\nhigh_resolution_clock: " << std::endl;
printClockDatastd::chrono::high_resolution_clock();
std::cout << "\nsteady_clock: " << std::endl;
printClockDatastd::chrono::steady_clock();
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
system_clock:
high_resolution_clock:
steady_clock:
#endif
#if 0// util/chrono1.cpp 2021年03月21日 星期日 16时17分32秒
#include
#include
#include
#include
std::string asString (const std::chrono::system_clock::time_point& tp){
std::time_t t = std::chrono::system_clock::to_time_t(tp);
std::string ts = std::ctime(&t);
ts.resize(ts.size()-1);
return ts;
}
int main(){
std::chrono::system_clock::time_point tp;
std::cout << "epoch: " << asString(tp) << std::endl;
tp = std::chrono::system_clock::now();
std::cout << "now: " << asString(tp) << std::endl;
tp = std::chrono::system_clock::time_point::min();
std::cout << "min: " << asString(tp) << std::endl;
tp = std::chrono::system_clock::time_point::max();
std::cout << "max: " << asString(tp) << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
epoch: Thu Jan 1 08:00:00 1970
now: Sun Mar 21 16:23:08 2021
min: Tue Sep 21 08:18:27 1677
max: Sat Apr 12 07:47:16 2262
#endif
#if 0// util/chrono2.cpp 2021年03月21日 星期日 16时17分32秒
#include
#include
#include
#include
std::string asString (const std::chrono::system_clock::time_point& tp){
std::time_t t = std::chrono::system_clock::to_time_t(tp);
std::string ts = std::ctime(&t);
ts.resize(ts.size()-1);
return ts;
}
int main(){
typedef std::chrono::duration
std::chrono::time_point tp;
std::cout << "epoch: " << asString(tp) << std::endl;
tp += Days(1) + std::chrono::hours(23) + std::chrono::minutes(55);
std::cout << "later: " << asString(tp) << std::endl;
auto diff = tp - std::chrono::system_clock::time_point();
std::cout << "diff: "
<< std::chrono::duration_cast(diff).count()
<< " minutes(s)" << std::endl;
Days days = std::chrono::duration_cast(diff);
std::cout << "diff: " << days.count() << " day(s)" << std::endl;
tp -= std::chrono::hours(24* 365);
std::cout << "-1 year: " << asString(tp) << std::endl;
tp -= std::chrono::duration>(50);
std::cout << "-50 years: " << asString(tp) << std::endl;
tp -= std::chrono::duration>(50);
std::cout << "-50 years: " << asString(tp) << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
epoch: Thu Jan 1 08:00:00 1970
later: Sat Jan 3 07:55:00 1970
diff: 2875 minutes(s)
diff: 1 day(s)
-1 year: Fri Jan 3 07:55:00 1969
-50 years: Thu Jan 16 07:55:00 1919
-50 years: Wed Jan 27 08:00:43 1869
#endif
#if 0//util/timepoint1.cpp 2021年03月21日 星期日 19时14分31秒
#include
#include
#include “timepoint.hpp”
int main(){
auto tp1 = makeTimePoint(2010, 01, 01, 00, 00);
std::cout << asString(tp1) << std::endl;
auto tp2 = makeTimePoint(2011, 05, 23, 13, 44);
std::cout << asString(tp2) << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
Fri Jan 1 00:00:00 2010
Mon May 23 13:44:00 2011
#endif
#if 0//stl/vector1.cpp 2021年03月21日 星期日 19时18分30秒
#include
#include
int main(){
std::vector coll;
for(int i = 1; i <= 6; ++i){
coll.push_back(i);
}
for(int i = 0; i < coll.size(); ++i){
std::cout << coll[i] << ’ ';
}
std::cout << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
1 2 3 4 5 6
#endif
#if 0//stl/deque1.cpp 2021年03月21日 星期日 19时21分10秒
#include
#include
int main(){
std::deque coll;
for(int i = 1; i <= 6; ++i){
coll.push_front(i*1.1);
}
for(int i = 0; i < coll.size(); ++i){
std::cout << coll[i] << ’ ';
}
std::cout << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
6.6 5.5 4.4 3.3 2.2 1.1
#endif
#if 0//stl/array1.cpp
#include
#include
#include
int main(){
std::array
for(int i = 0; i < coll.size(); ++i){
std::cout << i << ": " << coll[i] << std::endl;
}
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
0: hello
1: world
2: c++
3:
4:
#endif
#if 0//stl/list1.cpp 2021年03月21日 星期日 19时24分06秒
#include
#include
int main(){
std::list coll;
for(char c = ‘a’; c <= ‘z’; ++c){
coll.push_back©;
}
for(auto elem : coll){
std::cout << elem << ’ ';
}
std::cout << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
a b c d e f g h i j k l m n o p q r s t u v w x y z
#endif
#if 0//stl/list2.cpp 2021年03月21日 星期日 19时26分28秒
#include
#include
int main(){
std::list coll;
for(char c = ‘a’; c <= ‘z’; ++c){
coll.push_back©;
}
while (!coll.empty()){
std::cout << coll.front() << ’ ';
coll.pop_front();
}
std::cout << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
a b c d e f g h i j k l m n o p q r s t u v w x y z
#endif
#if 0//stl/forwardlist1.cpp 2021年03月21日 星期日 19时29分14秒
#include
#include
int main(){
std::forward_list coll {2, 3, 5, 7, 11, 13, 17};
coll.resize(9);
coll.resize(10, 99);
for(auto elem: coll){
std::cout << elem << ’ ';
}
std::cout << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
2 3 5 7 11 13 17 0 0 99
#endif
#if 0//stl/multiset1.cpp 2021年03月21日 星期日 19时32分29秒
#include
#include
#include
int main(){
std::multisetstd::string cities{
“Braunschweig”, “Hanover”, “Frankfurt”, “New York”,
“Chicago”, “Toronto”, “Paris”, “Frankfurt”};
for(const auto & elem : cities){
std::cout << elem << " ";
}
std::cout << std::endl;
cities.insert({“London”, “Munich”, “Hanover”, “Braunschweig”});
for(const auto& elem: cities){
std::cout << elem << " ";
}
std::cout << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
Braunschweig Chicago Frankfurt Frankfurt Hanover New York Paris Toronto
Braunschweig Braunschweig Chicago Frankfurt Frankfurt Hanover Hanover London Munich New York Paris Toronto
#endif
#if 0//stl/multimap1.cpp 2021年03月21日 星期日 19时37分48秒
#include
#include
#include
int main(){
std::multimap
coll = {{5, “tagged”}, {2, “a”}, {1, “this”},
{4, “of”}, {6, “strings”},{1, “is”}, {3, “multimap”}};
for(auto elem : coll){
std::cout << elem.second << ’ ';
}
std::cout << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
this is a multimap of tagged strings
#endif
#if 0//stl/unordmultiset1.cpp 2021年03月21日 星期日 19时42分39秒
#include
#include
#include
int main(){
std::unordered_multisetstd::string cities{
“Braunschweig”, “Hanover”, “Frankfurt”, “New York”,
“Chicago”, “Toronto”, “Paris”, “Frankfurt”
};
for(const auto& elem: cities){
std::cout << elem << " ";
}
std::cout << std::endl;
cities.insert({“London”, “Munich”, “Hanover”, “Braunschweig”});
for(const auto& elem: cities){
std::cout << elem << " ";
}
std::cout << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
Paris Toronto Chicago New York Frankfurt Frankfurt Hanover Braunschweig
Munich London Frankfurt Frankfurt New York Braunschweig Braunschweig Chicago Toronto Hanover Hanover Paris
#endif
#if 0//stl/unordmap1.cpp 2021年03月21日 星期日 19时47分07秒
#include
#include
#include
int main(){
std::unordered_map
for(std::pair
elem.second *= elem.second;
}
for(const auto & elem : coll){
std::cout << elem.first << ": " << elem.second << std::endl;
}
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
struppi: 138.533
tim: 98.01
#endif
#if 0//stl/assoarray1.cpp 2021年03月21日 星期日 19时51分39秒
#include
#include
#include
int main(){
std::unordered_map
coll[“VAT1”] = 0.16;
coll[“VAT2”] = 0.07;
coll[“Pi”] = 3.14159;
coll[“an arbitrary number”] = 4983.223;
coll[“Null”] = 0;
coll["VAT1"] += 0.03;
std::cout << "VAT difference: " << coll["VAT1"] - coll["VAT2"] << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
VAT difference: 0.12
#endif
#if 0//stl/list1old.cpp 2021年03月22日 星期一 19时02分22秒
#include
#include
int main(){
std::list coll;
for(char c =‘a’; c <= ‘z’;++c){
coll.push_back©;
}
std::list::const_iterator pos;
for(pos = coll.begin(); pos != coll.end(); ++ pos){
std::cout << *pos << ’ ';
}
std::cout << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
a b c d e f g h i j k l m n o p q r s t u v w x y z
#endif
#if 0//stl/set1.cpp 2021年03月22日 星期一 19时06分32秒
#include
#include
int main(){
typedef std::set IntSet;
IntSet coll;
coll.insert(3);
coll.insert(1);
coll.insert(5);
coll.insert(4);
coll.insert(1);
coll.insert(6);
coll.insert(2);
IntSet::const_iterator pos;
for(pos = coll.begin(); pos != coll.end(); ++pos){
std::cout << *pos << ' ';
}
std::cout << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
1 2 3 4 5 6
#endif
#if 0//stl/unordmultiset2.cpp 2021年03月22日 星期一 19时12分10秒
#include
#include
int main(){
std::unordered_multiset coll;
coll.insert({1, 3, 5, 7, 11, 13, 17, 19, 23, 27, 1});
for(auto elem : coll){
std::cout << elem << ’ ';
}
std::cout << std::endl;
coll.insert(25);
for(auto elem : coll){
std::cout << elem << ’ ';
}
std::cout << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
23 19 17 13 11 7 5 3 27 1 1
25 23 19 17 13 11 7 5 3 27 1 1
#endif
#if 0//stl/algo1.cpp 2021年03月22日 星期一 19时16分18秒
#include
#include
#include
int main(){
std::vector coll = {2, 5, 4, 1, 6, 3};
auto maxpos = min_element(coll.cbegin(), coll.cend());
std::cout << "max: " << *maxpos << std::endl;
std::sort(coll.begin(), coll.end());
auto pos3 = std::find(coll.begin(), coll.end(), 3);
reverse(pos3, coll.end());
for(auto elem : coll){
std::cout << elem << ' ';
}
std::cout << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
max: 1
1 2 6 5 4 3
#endif
#if 0//stl/find1.cpp 2021年03月22日 星期一 20时17分21秒
#include
#include
#include
int main(){
std::list coll;
for(int i = 20; i <= 40; ++i){
coll.push_back(i);
}
auto pos3 = std::find(coll.begin(), coll.end(), 3);
reverse(pos3, coll.end());
std::list::iterator pos25, pos35;
pos25 = std::find(coll.begin(), coll.end(), 25);
pos35 = std::find(coll.begin(), coll.end(), 35);
std::cout << "max: " << *max_element(pos25, pos35) << std::endl;
std::cout << "max: " << *max_element(pos25, ++pos35) << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
max: 34
max: 35
#endif
#if 0//stl/remove3.cpp 2021年03月26日 星期五 20时10分51秒
#include
#include
#include
#include
int main(){
std::set coll {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::copy(coll.cbegin(), coll.cend(),
std::ostream_iterator(std::cout, " "));
std::cout << std::endl;
int num = coll.erase(3);
std::cout << "number of removed elements: " << num << std::endl;
std::copy(coll.cbegin(), coll.cend(),
std::ostream_iterator(std::cout, " "));
std::cout << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
1 2 3 4 5 6 7 8 9
number of removed elements: 1
1 2 4 5 6 7 8 9
#endif
#if 0//stl/remove4.cpp 2021年03月26日 星期五 20时16分53秒
#include
#include
#include
int main(){
std::list coll;
for(int i = 1; i <= 6; ++i){
coll.push_front(i);
coll.push_back(i);
}
coll.erase (remove(coll.begin(), coll.end(), 3), coll.end());
coll.remove(4);
return 0;
}
#endif
#if 0//stl/foreach1.cpp
#include
#include
#include
void print(int elem){
std::cout << elem << ’ ';
}
int main(){
std::vector coll;
for(int i = 1; i <= 9; ++i){
coll.push_back(i);
}
for_each(coll.cbegin(), coll.cend(),print);
std::cout << std::endl;
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
1 2 3 4 5 6 7 8 9
#endif
#if 0//stl/transform1.cpp 2021年03月26日 星期五 21时11分33秒
#include
#include
#include
#include
#include
#include “print.hpp”
int square(int value){
return value*value;
}
int main(){
std::set coll1;
std::vector coll2;
for(int i = 1; i <= 9; ++i){
coll1.insert(i);
}
PRINT_ELEMENTS(coll1, "initialized: ");
//std::transform(coll1, "initialized: "); //多打出来的
std::transform(coll1.cbegin(), coll1.cend(),
std::back_inserter(coll2), square);
PRINT_ELEMENTS(coll2, "squared: ");
return 0;
}
wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
initialized: 1 2 3 4 5 6 7 8 9
squared: 1 4 9 16 25 36 49 64 81
#endif
#if 0//stl/prime1.cpp p226 2021年03月27日 星期六 07时58分42秒
#include
#include
#include
#include
bool isPrime(int number){
number = abs(number);
if(number == 0 || number == 1){
return false;
}
int divisor;
for(divisor = number/2; number%divisor != 0; --divisor){
;
}
return divisor == 1;
}
int main(){
std::list coll;
for(int i = 24; i <= 30; ++i){
coll.push_back(i);
}
auto pos = find_if(coll.cbegin(), coll.cend(),
isPrime);
if(pos != coll.end()){
std::cout << *pos << " is first prime number found" << std::endl;
}else{
std::cout << “no prime number found” << std::endl;
}
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
29 is first prime number found
#endif
#if 0 //sort1.cpp 2021年03月27日 星期六 08时04分30秒
#include
#include
#include
#include
// 未调试过!!!!! 对‘Person::lastnameabi:cxx11 const’未定义的引用
class Person{
public:
std::string firstname() const;
std::string lastname() const;
};
bool personSortCriterion(const Person& p1, const Person& p2){
return p1.lastname() < p2.lastname() ||
(p1.lastname() == p2.lastname() &&
p1.firstname() < p2.firstname());
}
int main(){
std::deque coll;
sort(coll.begin(), coll.end(),
personSortCriterion);
}
#endif
#if 0//stl/lambda1.cpp
#include
#include
#include
//查找集合内"数值在x和y之间"的第一个元素
//提供了一种能力可以直接描述"传给transform()"的某种函数行为
int main(){
std::deque coll {1, 3, 19, 5, 13, 7, 11, 2, 17};
int x = 5;
int y = 12;
auto pos = find_if(coll.cbegin(), coll.cend(),
[=](int i){
return i > x && i < y;
});
std::cout << "first elem > 5 and < 12: " << *pos << std::endl;
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
first elem > 5 and < 12: 7
#endif
#if 0 //sort2.cpp 2021年03月27日 星期六 08时04分30秒
#include
#include
#include
#include
using namespace std;
// 未调试过!!!!! 对‘Person::lastnameabi:cxx11 const’未定义的引用
class Person{
public:
string firstname() const;
string lastname() const;
};
int main(){
std::deque coll;
std::sort(coll.begin(), coll.end(),
[](const Person& p1, const Person& p2){
return p1.lastname() < p2.lastname() ||
(p1.lastname() == p2.lastname() &&
p1.firstname() < p2.firstname());
});
}
#endif
#if 0//stl/foreach2.cpp 2021年03月27日 星期六 08时45分04秒
#include
#include
#include
class PrintInt{
public:
void operator()(int elem) const{
std::cout << elem << ’ ';
}
};
int main(){
std::vector coll;
for(int i = 1; i <= 9; ++i){
coll.push_back(i);
}
for_each(coll.cbegin(), coll.cend(),
PrintInt());
std::cout << std::endl;
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
1 2 3 4 5 6 7 8 9
#endif
#if 0//stl/add1.cpp 2021年03月27日 星期六 08时48分39秒
#include
#include
#include
#include “print.hpp”
class AddValue{
private:
int theValue;
public:
AddValue(int v) : theValue(v){
}
void operator()(int & elem) const{
elem += theValue;
}
};
int main(){
std::list coll;
for(int i = 1; i <= 9; ++i){
coll.push_back(i);
}
PRINT_ELEMENTS(coll, "initialized: ");
for_each(coll.begin(), coll.end(),
AddValue(10));
PRINT_ELEMENTS(coll, "after adding 10: ");
for_each(coll.begin(), coll.end(),
AddValue(*coll.begin()));
PRINT_ELEMENTS(coll, "after adding first element: ");
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
initialized: 1 2 3 4 5 6 7 8 9
after adding 10: 11 12 13 14 15 16 17 18 19
after adding first element: 22 23 24 25 26 27 28 29 30
#endif
#if 0//stl/fo1.cpp 2021年03月27日 星期六 08时55分45秒 p240
#include
#include
#include
#include
#include “print.hpp”
int main(){
std::deque coll {1, 2, 3, 5, 7, 11, 13, 17, 19};
PRINT_ELEMENTS(coll, "initialized: ");
transform(coll.cbegin(), coll.cend(),
coll.begin(),
std::negate());
PRINT_ELEMENTS(coll, "negated: ");
transform(coll.cbegin(), coll.cend(),
coll.cbegin(),
coll.begin(),
std::multiplies());
PRINT_ELEMENTS(coll, "squared: ");
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
initialized: 1 2 3 5 7 11 13 17 19
negated: -1 -2 -3 -5 -7 -11 -13 -17 -19
squared: 1 4 9 25 49 121 169 289 361
#endif
#if 0//stl/bind1.cpp 2021年03月27日 星期六 19时16分15秒
#include
#include
#include
#include
#include
#include
#include “print.hpp”
//using namespace std::placeholders;
int main(){
std::set
std::deque coll2;
PRINT_ELEMENTS(coll1, "initialized: ");
transform(coll1.cbegin(), coll1.cend(),
std::back_inserter(coll2),
std::bind(std::multiplies(), std::placeholders::_1, 10));
PRINT_ELEMENTS(coll2, "transformed: ");
std::replace_if(coll2.begin(), coll2.end(),
std::bind(std::equal_to(), std::placeholders::_1, 70), 42);
PRINT_ELEMENTS(coll2, "replaced: ");
coll2.erase(std::remove_if(coll2.begin(), coll2.end(),
std::bind(std::logical_and(),
std::bind(std::greater_equal(), std::placeholders::_1, 50),
std::bind(std::less_equal(), std::placeholders::_1, 80))), coll2.end() );
PRINT_ELEMENTS(coll2, "removed: ");
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
initialized: 9 8 7 6 5 4 3 2 1
transformed: 90 80 70 60 50 40 30 20 10
replaced: 90 80 42 60 50 40 30 20 10
removed: 90 42 40 30 20 10
#endif
#if 0//stl/iterbug.cpp p247 2021年03月27日 星期六 19时19分10秒
#include
#include
#include
int main(){
std::vector coll1;
std::vector coll2;
std::vector::iterator pos = coll1.begin();
reverse(++pos, coll1.end());
for(int i = 1; i <= 9; ++i){
coll1.push_back(i);
}
std::copy(coll1.cbegin(), coll1.cend(),
coll2.begin());
std::copy(coll1.cbegin(), coll1.cend(),
coll1.begin());
return 0;
}
#endif
#if 0//cont/array1.cpp 2021年03月27日 星期六 19时24分43秒 p268
#include
#include
#include
#include
#include
#include “print.hpp”
int main(){
std::array
PRINT_ELEMENTS(a);
a.back() = 9999999;
a[a.size()-2] = 42;
PRINT_ELEMENTS(a);
std::cout << "sum: "
<< std::accumulate(a.begin(), a.end(), 0)
<< std::endl;
transform(a.begin(), a.end(),
a.begin(),
std::negate());
PRINT_ELEMENTS(a);
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
11 22 33 44 0 0 0 0 0 0
11 22 33 44 0 0 0 0 42 9999999
sum: 10000151
-11 -22 -33 -44 0 0 0 0 -42 -9999999
#endif
#if 0//cont/vector1.cpp p279 2021年03月27日 星期六 19时31分25秒
#include
#include
#include
#include
#include
int main(){
std::vectorstd::string sentence;
sentence.reserve(5);
sentence.push_back("Hello, ");
sentence.insert(sentence.end(), {“how”, “are”, “you”, “?”});
std::copy(sentence.cbegin(), sentence.cend(),
std::ostream_iterator(std::cout, " "));
std::cout << std::endl;
std::cout << " max_size(): " << sentence.max_size() << std::endl;
std::cout << " size(): " << sentence.size() << std::endl;
std::cout << " capacity(): " << sentence.capacity() << std::endl;
swap(sentence[1], sentence[3]);
sentence.insert(std::find(sentence.begin(), sentence.end(), "?"), "always");
sentence.back() = "!";
std::copy(sentence.cbegin(), sentence.cend(),
std::ostream_iterator(std::cout, " "));
std::cout << std::endl;
std::cout << " size(): " << sentence.max_size() << std::endl;
std::cout << " capacity(): " << sentence.capacity() << std::endl;
sentence.pop_back();
sentence.pop_back();
sentence.shrink_to_fit();
std::cout << " size(): " << sentence.max_size() << std::endl;
std::cout << " capacity(): " << sentence.capacity() << std::endl;
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
Hello, how are you ?
max_size(): 288230376151711743
size(): 5
capacity(): 5
Hello, you are how always !
size(): 288230376151711743
capacity(): 10
size(): 288230376151711743
capacity(): 4
#endif
#if 0//cont/deque1.cpp 2021年03月27日 星期六 19时46分28秒
#include
#include
#include
#include
#include
int main(){
std::dequestd::string coll;
coll.assign (3, std::string(“string”));
coll.push_back(“last string”);
coll.push_front(“first string”);
std::copy(coll.cbegin(), coll.cend(),
std::ostream_iterator(std::cout, "\n"));
std::cout << std::endl;
coll.pop_front();
coll.pop_back();
for(unsigned i = 1; i < coll.size(); ++i){
coll[i] = "another " + coll[i];
}
coll.resize(4, "resized string");
std::copy(coll.cbegin(), coll.cend(),
std::ostream_iterator(std::cout, "\n"));
std::cout << std::endl;
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
first string
string
string
string
last string
string
another string
another string
resized string
#endif
#if 0//cont/list1.cpp p298 2021年03月27日 星期六 19时55分42秒
#include
#include
#include
#include
void printLists (const std::list& l1, const std::list& l2){
std::cout << "list1: ";
std::copy(l1.cbegin(), l1.cend(), std::ostream_iterator(std::cout, " "));
std::cout << std::endl << "list2: ";
std::copy(l1.cbegin(), l1.cend(), std::ostream_iterator(std::cout, " "));
std::cout << std::endl << std::endl;
}
int main(){
std::list list1, list2;
for(int i = 0; i < 6; ++i){
list1.push_back(i);
list2.push_front(i);
}
printLists(list1, list2);
list2.splice(std::find(list2.begin(), list2.end(), 3), list1);
printLists(list1, list2);
list2.splice(list2.end(), list2, list2.begin());
printLists(list1, list2);
list2.sort();
list1 = list2;
list2.unique();
printLists(list1, list2);
list1.merge(list2);
printLists(list1, list2);
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
list1: 0 1 2 3 4 5
list2: 0 1 2 3 4 5
list1:
list2:
list1:
list2:
list1: 0 0 1 1 2 2 3 3 4 4 5 5
list2: 0 0 1 1 2 2 3 3 4 4 5 5
list1: 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
list2: 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
#endif
#if 0 // p307 cont/forwardlistfind1.cpp 2021年03月28日 星期日 19时04分49秒
#include
#include “print.hpp”
#include
int main(){
std::forward_list list {1, 2, 3, 4, 5, 97, 98, 99};
auto posBefore = list.before_begin();
for(auto pos = list.begin(); pos != list.end(); ++pos, ++posBefore){
if(*pos % 2 == 0){
break;
}
}
list.insert_after(posBefore, 42);
PRINT_ELEMENTS(list);
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
1 42 2 3 4 5 97 98 99
#endif
#if 0//cont/forwardlistsplice1.cpp 2021年03月28日 星期日 19时21分54秒
#include
#include “print.hpp”
#include
int main(){
std::forward_list l1 {1, 2, 3, 4, 5};
std::forward_list l2 {97, 98, 99};
auto pos1 = l1.before_begin();
for(auto pb1 = l1.begin();pb1 != l1.end(); ++pb1, ++pos1){
if(*pb1 == 3){
break;
}
}
auto pos2 = l2.before_begin();
for(auto pb2 = l2.begin(); pb2 != l2.end(); ++pb2, ++pos2){
if(*pb2 == 99){
break;
}
}
l1.splice_after(pos2, l2, pos1);
PRINT_ELEMENTS(l1, "l1: ");
PRINT_ELEMENTS(l2, "l2: ");
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
l1: 1 2 4 5
l2: 97 98 3 99
#endif
#if 0//cont/forwardlist1.cpp 2021年03月28日 星期日 19时22分33秒
#include
#include
#include
#include
#include
void printLists(const std::string& s, const std::forward_list& l1,
const std::forward_list& l2){
std::cout << s << std::endl;
std::cout << " list1: ";
std::copy(l1.cbegin(), l1.cend(), std::ostream_iterator(std::cout, " "));
std::cout << std::endl << "list2: ";
std::copy(l2.cbegin(), l2.cend(), std::ostream_iterator(std::cout, " "));
std::cout << std::endl;
}
int main(){
std::forward_list list1 {1, 2, 3, 4};
std::forward_list list2 {77, 88, 99};
printLists("initial: ", list1, list2);
list2.insert_after(list2.before_begin(), 99);
list2.push_front(10);
list2.insert_after(list2.before_begin(), {10, 11, 12, 13});
printLists("6 new elems: ", list1, list2);
list1.insert_after(list1.before_begin(), list2.begin(), list2.end());
printLists("list2 into list1: ", list1, list2);
list2.erase_after(list2.begin());
list2.erase_after(std::find(list2.begin(), list2.end(), 99), list2.end());
printLists ("delete 2nd and after 99: ", list1, list2);
list1.sort();
list2 = list1;
list2.unique();
printLists("sorted and unique: ", list1, list2);
list1.merge(list2);
printLists("merged: ", list1, list2);
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
initial:
list1: 1 2 3 4
list2: 77 88 99
6 new elems:
list1: 1 2 3 4
list2: 10 11 12 13 10 99 77 88 99
list2 into list1:
list1: 10 11 12 13 10 99 77 88 99 1 2 3 4
list2: 10 11 12 13 10 99 77 88 99
delete 2nd and after 99:
list1: 10 11 12 13 10 99 77 88 99 1 2 3 4
list2: 10 12 13 10 99
sorted and unique:
list1: 1 2 3 4 10 10 11 12 13 77 88 99 99
list2: 1 2 3 4 10 11 12 13 77 88 99
merged:
list1: 1 1 2 2 3 3 4 4 10 10 10 11 11 12 12 13 13 77 77 88 88 99 99 99
list2:
#endif
#if 0//cont /seetrange1.cpp 2021年03月28日 星期日 19时42分07秒 p320
#include
#include
int main(){
std::set c;
c.insert(1);
c.insert(2);
//c.insert(3);
c.insert(4);
c.insert(5);
c.insert(6);
std::cout << "lower_bound(3): " << *c.lower_bound(3) << std::endl;
std::cout << "upper_bound(3): " << *c.upper_bound(3) << std::endl;
std::cout << "equal_range(3): " << *c.equal_range(3).first << " "
<< *c.equal_range(3).second << std::endl;
std::cout << std::endl;
std::cout << "lower_bound(5): " << *c.lower_bound(5) << std::endl;
std::cout << "upper_bound(5): " << *c.upper_bound(5) << std::endl;
std::cout << "equal_range(5): " << *c.equal_range(5).first << " "
<< *c.equal_range(5).second << std::endl;
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
lower_bound(3): 4
upper_bound(3): 4
equal_range(3): 4 4
lower_bound(5): 5
upper_bound(5): 6
equal_range(5): 5 6
#endif
#if 0//cont/set1.cpp p325 2021年03月28日 星期日 19时49分37秒
#include
#include
#include
#include
int main(){
std::set
coll1.insert({4, 3, 5, 1, 6, 2});
coll1.insert(5);
for(int elem : coll1){
std::cout << elem << ’ ';
}
std::cout << std::endl;
auto status = coll1.insert(4);
if(status.second){
std::cout << "4 inserted as element "
<< std::distance(coll1.begin(), status.first) + 1 << std::endl;
}
else{
std::cout << "4 already exists" << std::endl;
}
std::set coll2(coll1.cbegin(), coll1.cend());
std::copy(coll2.cbegin(), coll2.cend(), std::ostream_iterator(std::cout, " "));
std::cout << std::endl;
coll2.erase(coll2.begin(), coll2.find(3));
int num;
num = coll2.erase(5);
std::cout << num << " element(s) removed" << std::endl;
std::copy(coll2.cbegin(), coll2.cend(), std::ostream_iterator(std::cout, " "));
std::cout << std::endl;
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
6 5 4 3 2 1
4 already exists
1 2 3 4 5 6
1 element(s) removed
3 4 6
#endif
#if 0 //p 328//cont/setcmp1.cpp 2021年03月29日 星期一 19时07分40秒
#include
#include
#include “print.hpp”
class RuntimeCmp {
public:
enum cmp_mode{normal, reverse};
private:
cmp_mode mode;
public:
RuntimeCmp (cmp_mode m = normal) : mode(m){}
template
bool operator() (const T& t1, const T& t2) const {
return mode == normal ? t1 < t2 : t2 < t1;
}
bool operator == (const RuntimeCmp& rc) const {
return mode == rc.mode;
}
};
typedef std::set
int main(){
IntSet coll1 {4, 7, 5, 1, 6, 2, 5};
PRINT_ELEMENTS(coll1, "coll1: ");
RuntimeCmp reverse_order(RuntimeCmp::reverse);
IntSet coll2(reverse_order);
coll2 = {4, 7, 5, 1, 6, 2, 5};
PRINT_ELEMENTS(coll2, "coll2: ");
coll1 = coll2;
coll1.insert(3);
PRINT_ELEMENTS(coll1, "coll1: ");
if(coll1.value_comp() == coll2.value_comp()){
std::cout << "coll1 and coll2 have same sorting criterion"
<< std::endl;
}else {
std::cout << "coll1 and coll2 have a different sorting criterion"
<< std::endl;
}
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
coll1: 1 2 4 5 6 7
coll2: 7 6 5 4 2 1
coll1: 7 6 5 4 3 2 1
coll1 and coll2 have same sorting criterion
#endif
#if 0//cont /map1.cpp 2021年03月29日 星期一 19时23分45秒
#include
#include
#include
#include
int main(){
std::map
{“tim”, 9.9},
{“struppi”, 11.77}
};
for_each(coll.begin(), coll.end(),
[](std::pair& elem){
elem.second *= elem.second;
});
for_each(coll.begin(), coll.end(),
[](const std::map::value_type& elem){
std::cout << elem.first << ": " << elem.second << std::endl;
});
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
struppi: 138.533
tim: 98.01
#endif
#if 0//cont /map2.cpp 2021年03月29日 星期一 19时23分45秒
#include
#include
#include
#include
#include
int main(){
typedef std::map
StringFloatMap stocks;
stocks[“BASF”] = 369.50;
stocks[“VW”] = 413.50;
stocks[“Daimler”] = 819.00;
stocks[“BMW”] = 834.00;
stocks[“Siemens”] = 842.20;
StringFloatMap::iterator pos;
std::cout << std::left;
for(pos = stocks.begin(); pos != stocks.end(); ++ pos){
std::cout << "stock: " << std::setw(12) << pos->first
<< "price: " << pos->second << std::endl;
}
std::cout << std::endl;
for(pos = stocks.begin(); pos!= stocks.end(); ++pos){
pos->second *= 2;
}
for(pos = stocks.begin(); pos != stocks.end(); ++ pos){
std::cout << "stock: " << std::setw(12) << pos->first
<< "price: " << pos->second << std::endl;
}
std::cout << std::endl;
stocks["Volkswagen"] = stocks["VW"];
stocks.erase("VW");
for(pos = stocks.begin(); pos != stocks.end(); ++ pos){
std::cout << "stock: " << std::setw(12) << pos->first
<< "price: " << pos->second << std::endl;
}
std::cout << std::endl;
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
stock: BASF price: 369.5
stock: BMW price: 834
stock: Daimler price: 819
stock: Siemens price: 842.2
stock: VW price: 413.5
stock: BASF price: 739
stock: BMW price: 1668
stock: Daimler price: 1638
stock: Siemens price: 1684.4
stock: VW price: 827
stock: BASF price: 739
stock: BMW price: 1668
stock: Daimler price: 1638
stock: Siemens price: 1684.4
stock: Volkswagen price: 827
错误: " ‘strdup’ was not declared in this scope "
本文地址: http://blog.csdn.net/caroline_wendy/article/details/24041455
函数名: strdup; 功能: 将串拷贝到新建的位置处; 用法: char *strdup(char *str);
strdup属于GNU C++的函数, 不是标准(std)C++的函数, 需要修改参数:
把"-std=c++11"修改为"-std=gnu++0x", 即可.
————————————————
版权声明:本文为CSDN博主「SpikeKing」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/caroline_wendy/article/details/24041455
#endif
#if 0 // cont /multimap1.cpp 2021年03月29日 星期一 19时58分15秒
#include
#include
#include
#include
int main(){
std::multimap
dict.insert({ {“day”, “Tag”}, {“strange”, “fremd”},
{“car”, “Auto”}, {“smart”, “elegant”},
{“trait”, “Merkmal”}, {“strange”, “seltsam”},
{“smart”, “raffiniert”}, {“smart”, “klug”},
{“clever”, “raffiniert”} });
std::cout.setf(std::ios::left, std::ios::adjustfield);
std::cout << ’ ’ << std::setw(10) << "english "
<< "german " << std::endl;
std::cout << std::setfill(’-’) << std::setw(20) << “”
<< std::setfill(’ ') << std::endl;
for(const auto& elem : dict){
std::cout << ’ ’ << std::setw(10) << elem.first
<< elem.second << std::endl;
}
std::cout << std::endl;
std::string word("smart");
std::cout << word << ": " << std::endl;
for(auto pos = dict.lower_bound(word);
pos != dict.upper_bound(word);
++pos){
std::cout << " " << pos->second << std::endl;
}
word = ("raffiniert");
std::cout << word << ": " << std::endl;
for(const auto& elem : dict){
if(elem.second == word){
std::cout << " " << elem.first << std::endl;
}
}
return 0;
car Auto
clever raffiniert
day Tag
smart elegant
smart raffiniert
smart klug
strange fremd
strange seltsam
trait Merkmal
smart:
elegant
raffiniert
klug
raffiniert:
clever
smart
#endif
#if 0//cont /mapfind1.cpp p350 2021年03月31日 星期三 19时11分25秒
#include
#include
#include
#include
int main(){
std::map
auto posKey = coll.find(3.0);
if(posKey != coll.end()){
std::cout << “key 3.0 found (”
<< posKey->first << ": "
<< posKey->second << “)” << std::endl;
}
auto posVal = std::find_if(coll.begin(), coll.end(),
[](const std::pair
return elem.second == 3.0;
});
if(posVal != coll.end()){
std::cout << “value 3.0 found (”
<< posVal->first << ": "
<< posVal->second << “)” << std::endl;
}
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
key 3.0 found (3: 2)
value 3.0 found (4: 3)
#endif
#if 0//cont/mapcmp1.cpp p351 2021年03月31日 星期三 19时19分06秒
#include
#include
#include
#include
#include
#include
class RuntimeStringCmp{
public:
enum cmp_mode{normal, nocase};
private:
const cmp_mode mode;
static bool nocase_compare(char c1, char c2){
return std::toupper(c1) < std::toupper(c2);
}
public:
RuntimeStringCmp(cmp_mode m = normal): mode(m){
}
bool operator()(const std::string& s1, const std::string& s2) const{
if(mode == normal){
return s1 < s2;
}else{
return std::lexicographical_compare(s1.begin(), s1.end(),
s2.begin(), s2.end(),
nocase_compare);
}
}
};
typedef std::map
void fillAndPrint(StringStringMap& coll);
int main(){
StringStringMap coll1;
fillAndPrint(coll1);
RuntimeStringCmp ignorecase(RuntimeStringCmp::nocase);
StringStringMap coll2(ignorecase);
fillAndPrint(coll2);
return 0;
}
void fillAndPrint(StringStringMap& coll){
coll[“Deutschland”] = “Germany”;
coll[“deutsch”] = “German”;
coll[“Haken”] = “snag”;
coll[“arbeiten”] = “work”;
coll[“Hund”] = “dog”;
coll[“gehen”] = “go”;
coll[“Unternehemen”] = “enterprise”;
coll[“Unternehemen”] = “undertake”;
coll[“gehen”] = “walk”;
coll[“Bestatter”] = “undertaker”;
std::cout.setf(std::ios::left, std::ios::adjustfield);
for(const auto & elem : coll){
std::cout << std::setw(15) << elem.first << " "
<< elem.second << std::endl;
}
std::cout << std::endl;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
Bestatter undertaker
Deutschland Germany
Haken snag
Hund dog
Unternehemen undertake
arbeiten work
deutsch German
gehen walk
arbeiten work
Bestatter undertaker
deutsch German
Deutschland Germany
gehen walk
Haken snag
Hund dog
Unternehemen undertake
#endif
#if 0//cont/unordset1.cpp p375 2021年03月31日 星期三 19时47分01秒
#include
#include
#include
#include “print.hpp”
int main(){
std::unordered_set coll {1, 2, 3, 5, 7, 11, 13, 17, 19, 77};
PRINT_ELEMENTS(coll);
coll.insert({-7, 17, 33, -11, 17, 19, 1, 13});
PRINT_ELEMENTS(coll);
coll.erase(33);
coll.insert(std::accumulate(coll.begin(), coll.end(), 0));
PRINT_ELEMENTS(coll);
if(coll.find(19) != coll.end()){
std::cout << "19 is available" << std::endl;
}
std::unordered_set::iterator pos;
for(pos = coll.begin(); pos != coll.end();){
if(*pos < 0){
pos = coll.erase(pos);
}else{
++pos;
}
}
PRINT_ELEMENTS(coll);
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
19 17 77 11 7 5 3 13 2 1
-11 33 -7 1 2 13 3 5 7 11 77 17 19
-11 137 -7 1 2 13 3 5 7 11 77 17 19
19 is available
137 1 2 13 3 5 7 11 77 17 19
#endif
#if 0 //cont/hasfunc1.cpp p378 2021年03月31日 星期三 19时53分52秒
#include
#include
#include
#include “hashval.hpp”
#include “print.hpp”
class Customer{
private:
std::string fname;
std::string lname;
long no;
public:
Customer(const std::string& fn, const std::string& ln, long n)
: fname(fn), lname(ln), no(n) { }
friend std::ostream& operator << (std::ostream & strm, const Customer & c){
return strm << “[” << c.fname << “,” << c.lname << “,”
<< c.no << “]”;
}
friend class CustomerHash;
friend class CustomerEqual;
};
class CustomerHash{
public:
std::size_t operator() (const Customer & c) const {
return hash_val(c.fname, c.lname, c.no);
}
};
class CustomerEqual{
public:
bool operator()(const Customer& c1, const Customer& c2) const{
/*
错误:static assertion failed: key equality predicate must be invocable with two arguments of key type
解决方法:: 第二个, 少了const
//https://stackoverflow.com/questions/63417810/unordered-map-with-custom-hash-function-and-comparison-predicate-gives-compilati
bool operator()(struct keys const& k1, struct keys const& k2)
must be const
// VVVVV
bool operator()(struct keys const& k1, struct keys const& k2) const
You can also see it in the error message that the function must be callable on a const reference of the object
// VVVVV V
static_assert(__is_invocable
I couldn’t find anything in the standard that explicitly says, it must be const, at most in the named requirement for comparators:
[...] evaluation of that expression is not allowed to call non-const functions through the dereferenced iterators.
*/
return c1.no == c2.no;
}
};
int main(){
std::unordered_set
custset.insert(Customer(“nico”,“josuttis”, 42));
PRINT_ELEMENTS(custset);
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
[nico,josuttis,42]
#endif
#if 0//p379 //cont/hasfunc2.cpp 2021年04月01日 星期四 19时08分17秒
#include
#include
#include
#include “hashval.hpp”
#include “print.hpp”
using namespace std;
class Customer{
private:
std::string fname;
std::string lname;
long no;
public:
Customer(const std::string& fn, const std::string& ln, long n)
: fname(fn), lname(ln), no(n) { }
std::string firstname() const { return fname; };
std::string lastname() const { return lname; };
long number() const { return no; };
friend std::ostream& operator << (std::ostream & strm, const Customer & c){
return strm << "[" << c.fname << "," << c.lname << ","
<< c.no << "]";
}
};
int main(){
/*
Note that you have to use decltype to yield the type of the lambda to be able to pass it as template
argument to the declaration of the unordered container. The reason is that for lambdas, no default
constructor and assignment operator are defined. Therefore, you also have to pass the lambdas to
the constructor. This is possible only as second and third arguments. Thus, you have to specify the
initial bucket size 10 in this case.
————————————————
版权声明:本文为CSDN博主「Alex_晴天小猪」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/icevmj/article/details/78098078
*/
auto hash = [] (const Customer& c){
return hash_val(c.firstname(), c.lastname(), c.number());
};
auto eq = [] (const Customer& c1, Customer& c2){
return c1.number() == c2.number();
};
unordered_set
custset.insert(Customer(“nico”, “josuttis”, 42));
PRINT_ELEMENTS(custset);
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
[nico,josuttis,42]
#endif
#if 0 //cont/unordinspect1.cpp 2021年04月01日 星期四 19时49分51秒 p382
#include
#include
#include “buckets.hpp”
int main(){
std::unordered_set intset {1, 2, 3, 5, 7, 11, 13, 17, 19};
printHashTableState(intset);
intset.insert({-7, 17, 33, 4});
printHashTableState(intset);
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
size: 9
buckets: 11
load factor: 0.818182
max load factor1
chaining style: singly-linked
data:
b[ 0]: 11
b[ 1]: 1
b[ 2]: 13 2
b[ 3]: 3
b[ 4]:
b[ 5]: 5
b[ 6]: 17
b[ 7]: 7
b[ 8]: 19
b[ 9]:
b[10]:
size: 12
buckets: 23
load factor: 0.521739
max load factor1
chaining style: singly-linked
data:
b[ 0]:
b[ 1]: 1
b[ 2]: 2
b[ 3]: 3
b[ 4]: 4
b[ 5]: 5
b[ 6]:
b[ 7]: 7
b[ 8]:
b[ 9]:
b[10]: 33
b[11]: 11
b[12]:
b[13]: 13
b[14]:
b[15]:
b[16]:
b[17]: 17
b[18]:
b[19]: 19
b[20]:
b[21]:
b[22]: -7
#endif
#if 0 //cont/unordmultimap1.cpp p383 2021年04月01日 星期四 19时53分17秒
#include
#include
#include
#include
#include “buckets.hpp”
int main(){
std::unordered_multimap
{“day”, “Tag”},
{“strange”, “fremd”},
{“car”, “Auto”},
{“smart”, “elegant”},
{“trait”, “Merkmal”},
{“strange”, “seltsam”}
};
printHashTableState(dict);
dict.insert({{"smart", "raffiniert"},
{"smart", "klug"},
{"clever", "raffiniert"}
});
printHashTableState(dict);
dict.max_load_factor(0.7);
printHashTableState(dict);
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
size: 6
buckets: 7
load factor: 0.857143
max load factor1
chaining style: singly-linked
data:
b[ 0]: [trait, Merkmal]
b[ 1]: [strange, seltsam] [strange, fremd]
b[ 2]: [day, Tag]
b[ 3]: [smart, elegant]
b[ 4]:
b[ 5]: [car, Auto]
b[ 6]:
size: 9
buckets: 17
load factor: 0.529412
max load factor1
chaining style: singly-linked
data:
b[ 0]: [car, Auto]
b[ 1]:
b[ 2]:
b[ 3]:
b[ 4]:
b[ 5]:
b[ 6]: [strange, seltsam] [strange, fremd] [smart, klug] [smart, raffiniert] [smart, elegant]
b[ 7]:
b[ 8]:
b[ 9]:
b[10]: [clever, raffiniert]
b[11]:
b[12]: [trait, Merkmal]
b[13]:
b[14]:
b[15]: [day, Tag]
b[16]:
size: 9
buckets: 17
load factor: 0.529412
max load factor0.7
chaining style: singly-linked
data:
b[ 0]: [car, Auto]
b[ 1]:
b[ 2]:
b[ 3]:
b[ 4]:
b[ 5]:
b[ 6]: [strange, seltsam] [strange, fremd] [smart, klug] [smart, raffiniert] [smart, elegant]
b[ 7]:
b[ 8]:
b[ 9]:
b[10]: [clever, raffiniert]
b[11]:
b[12]: [trait, Merkmal]
b[13]:
b[14]:
b[15]: [day, Tag]
b[16]:
#endif
#if 0//p386 cont/cstylearray1.cpp 2021年04月02日 星期五 19时04分41秒
#include
#include
#include
int main(){
int vals[] {33, 67, -4, 13, 5, 2};
std::vector v(std::begin(vals), std::end(vals));
std::copy(std::begin(v), std::end(v),
std::ostream_iterator(std::cout, " "));
std::cout << std::endl;
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
33 67 -4 13 5 2
#endif
#if 0 //cont/cstylearray1old.cpp 2021年04月02日 星期五 19时15分00秒
#include
#include
#include
#include
int main(){
int coll[] {5, 6, 2, 4, 1, 3};
std::transform (coll, coll + 6,
coll,
coll,
std::multiplies());
std::sort(coll + 1, coll+6);
//一定要确保区间尾端是最末元素的下一位置
std::copy(coll, coll+ 6,
std::ostream_iterator(std::cout, " "));
std::cout << std::endl;
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
25 1 4 9 16 36
#endif
#if 0 //cont/refsem1.cpp 2021年04月02日 星期五 19时15分17秒
#include
#include
#include
#include
#include
#include
class Item{
private:
std::string name;
float price;
public:
Item (const std::string& n, float p = 0) : name(n), price§ { }
std::string getName() const{
return name;
}
void setName(const std::string& n){
name = n;
}
float getPrice() const{
return price;
}
float setPrice(float p){
price = p;
}
};
template
void printItems (const std::string& msg, const Coll& coll){
std::cout << msg << std::endl;
for(const auto& elem : coll){
std::cout << ' ' << elem->getName() << ": "
<< elem->getPrice() << std::endl;
}
}
int main(){
typedef std::shared_ptr ItemPtr;
std::set allItems;
std::deque bestsellers;
bestsellers = { ItemPtr(new Item("Kong Yize", 20.10)),
ItemPtr(new Item("A Midsummer Nigth's Dream", 14.99)),
ItemPtr(new Item("The Maltese Falcon", 9.88)) };
allItems = { ItemPtr(new Item("Water", 0.44)),
ItemPtr(new Item("Pizza", 2.22))};
allItems.insert(bestsellers.begin(), bestsellers.end());
printItems("bestsellers: ", bestsellers);
printItems("all: ", allItems);
std::cout << std::endl;
std::for_each(bestsellers.begin(), bestsellers.end(),
[](std::shared_ptr- & elem){
elem->setPrice(elem->getPrice() * 2);
});
bestsellers[1] = *(std::find_if(allItems.begin(), allItems.end(),
[](std::shared_ptr
- elem){
return elem->getName() == "Pizza";
}));
bestsellers[0]->setPrice(44.77);
printItems("bestsellers: ", bestsellers);
printItems("all: ", allItems);
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
bestsellers:
Kong Yize: 20.1
A Midsummer Nigth’s Dream: 14.99
The Maltese Falcon: 9.88
all:
Kong Yize: 20.1
Water: 0.44
A Midsummer Nigth’s Dream: 14.99
The Maltese Falcon: 9.88
Pizza: 2.22
bestsellers:
Kong Yize: 44.77
Pizza: 2.22
The Maltese Falcon: 19.76
all:
Kong Yize: 44.77
Water: 0.44
A Midsummer Nigth’s Dream: 29.98
The Maltese Falcon: 19.76
Pizza: 2.22
#endif
#if 0//cont/sortset.cpp 2021年04月02日 星期五 19时34分12秒 p394
#include
#include
#include
#include
#include
int main(){
std::setstd::string coll((std::istream_iteratorstd::string(std::cin)),
std::istream_iteratorstd::string());
std::copy(coll.cbegin(), coll.cend(),
std::ostream_iteratorstd::string(std::cout, “\n”));
return 0;
}
#endif
#if 0
#include
#include
#include
#include
#include
int main(){
std::vectorstd::string coll((std::istream_iteratorstd::string(std::cin)),
std::istream_iteratorstd::string());
std::sort(coll.begin(), coll.end());
std::unique_copy(coll.cbegin(), coll.cend(),
std::ostream_iterator(std::cout, "\n"));
return 0;
}
#endif
#if 0//iter/itercategory1.cpp 2021年04月02日 星期五 19时45分02秒 p438
#include
#include
int main(){
std::vector coll;
for(int i = -3; i <= 9; ++i){
coll.push_back(i);
}
std::cout << "number/distance: " << coll.end()-coll.begin() << std::endl;
std::vector::iterator pos;
for(pos = coll.begin(); pos < coll.end(); ++pos){
std::cout << *pos << ’ ';
}
std::cout << std::endl;
for(int i = 0; i < coll.size(); ++i){
std::cout << coll.begin()[i] << ' ';
}
std::cout << std::endl;
for(pos = coll.begin(); pos < coll.end()-1; pos += 2){
std::cout << *pos << ' ';
}
std::cout << std::endl;
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
number/distance: 13
-3 -2 -1 0 1 2 3 4 5 6 7 8 9
-3 -2 -1 0 1 2 3 4 5 6 7 8 9
-3 -1 1 3 5 7
#endif
#if 0//iter/advance1.cpp 2021年04月02日 星期五 19时50分45秒 p442
#include
#include
#include
#include
int main(){
std::list coll;
for(int i = 1; i<= 9; ++i){
coll.push_back(i);
}
std::list::iterator pos= coll.begin();
std::cout << *pos << std::endl;
advance(pos, 3);
std::cout << *pos << std::endl;
advance(pos, -1);
std::cout << *pos << std::endl;
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
1
4
3
#endif
#if 0//iter/distance1.cpp 2021年04月02日 星期五 19时54分16秒 p445
#include
#include
#include
#include
int main(){
std::list coll;
for(int i = -3; i <= 9; ++i){
coll.push_back(i);
}
std::list::iterator pos;
pos = std::find(coll.begin(), coll.end(), 5);
if(pos != coll.end()){
std::cout << "difference between beginning and 5: "
<< distance(coll.begin(), pos) << std::endl;
}else{
std::cout << "5 not found" << std::endl;
}
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
difference between beginning and 5: 8
#endif
#if 0//iter /iterswap1.cpp p447 2021年04月03日 星期六 10时17分17秒
#include
#include
#include
#include
#include “print.hpp”
int main(){
std::list coll;
for(int i = 1; i <= 9; ++i){
coll.push_back(i);
}
PRINT_ELEMENTS(coll);
std::iter_swap(coll.begin(), next(coll.begin()));
PRINT_ELEMENTS(coll);
std::iter_swap(coll.begin(), prev(coll.end()));
PRINT_ELEMENTS(coll);
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
1 2 3 4 5 6 7 8 9
2 1 3 4 5 6 7 8 9
9 1 3 4 5 6 7 8 2
#endif
#if 0//iter/reviter1.cpp 2021年04月03日 星期六 10时20分41秒 p448
#include
#include
#include
void print(int elem){
std::cout << elem << ’ ';
}
int main(){
std::list coll {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::for_each(coll.begin(), coll.end(), print);
std::cout << std::endl;
std::for_each(coll.rbegin(), coll.rend(), print);
std::cout << std::endl;
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1
#endif
#if 0 //iter/reviter2.cpp 2021年04月03日 星期六 10时21分29秒
#include
#include
#include
#include
int main(){
std::vector coll {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::vector::const_iterator pos;
pos = find (coll.cbegin(), coll.cend(), 5);
std::cout << "pos: " << *pos <
std::cout << "rpos: " << *rpos << std::endl;
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
pos: 5
rpos: 4
#endif
#if 0//iter/reviter3.cpp p451 2021年04月03日 星期六 10时27分16秒
#include
#include
#include
#include
void print(int elem){
std::cout << elem << ’ ';
}
int main(){
std::deque coll {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::deque::const_iterator pos1;
pos1 = find(coll.cbegin(), coll.cend(), 2);
std::cout << std::endl;
std::deque::const_iterator pos2;
pos2 = find(coll.cbegin(), coll.cend(), 7);
std::for_each(pos1, pos2, print);
std::cout << std::endl;
std::deque::const_reverse_iterator rpos1(pos1);
std::deque::const_reverse_iterator rpos2(pos2);
std::for_each(rpos2, rpos1, print);
std::cout << std::endl;
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
2 3 4 5 6
6 5 4 3 2
#endif
#if 0//iter/reviter4.cpp p451 2021年04月03日 星期六 10时27分16秒
#include
#include
#include
#include
void print(int elem){
std::cout << elem << ’ ';
}
int main(){ }wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello #endif #if 0//iter/backinserter1.cpp p456 2021年04月03日 星期六 10时39分40秒 int main(){ }wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello #endif #if 0//iter/frontinserter1.cpp 2021年04月03日 星期六 10时45分59秒 int main(){ }wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello #endif int main(){ }wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello #endif #if 0 //iter/ostreamiter1.cpp p462 2021年04月04日 星期日 07时34分44秒 int main(){ }wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello #endif #if 0 // iter/istreamiter1.cpp p464 2021年04月04日 星期日 07时40分08秒 int main(){ #endif #if 0// p465 iter/advance2.cpp int main(){ #endif #if 0//iter/ assoiter1.cpp p473 2021年04月04日 星期日 08时09分33秒 int main(){ }wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello #endif #if 0//p477 fo/sort1.cpp 2021年04月04日 星期日 08时15分52秒 class PersonSortCriterion{ int main(){ } #if 0//p478 fo/sequence1.cpp 2021年04月04日 星期日 08时20分48秒 int main(){ #endif int main(){ }wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello #endif #if 0 //fo/foreach3.cpp p482 2021年04月05日 星期一 20时38分29秒 int main(){ // 36 / 8 = 4.5 #endif #if 0 //fo / removeif1.cpp p484 2021年04月05日 星期一 20时46分05秒 int main(){ }wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello #endif #if 0 //fo/bind1.cpp p488 2021年04月05日 星期一 20时52分11秒 int main(){ }wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello #endif
std::list coll {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::list::const_iterator pos;
pos = std::find(coll.cbegin(), coll.cend(), 5);
std::cout << "pos: " << *pos <std::list
pos: 5
rpos: 4
rrpos: 5
#include
#include
#include
#include
#include “print.hpp”
std::vector coll;
std::back_insert_iterator
*iter = 1;
iter++;
*iter = 2;
iter++;
*iter = 3;
PRINT_ELEMENTS(coll);std::back_inserter(coll) = 44;
std::back_inserter(coll) = 55;
PRINT_ELEMENTS(coll);
coll.reserve(2*coll.size());
std::copy(coll.begin(), coll.end(), std::back_inserter(coll));
PRINT_ELEMENTS(coll);
return 0;
1 2 3
1 2 3 44 55
1 2 3 44 55 1 2 3 44 55
#include
#include
#include
#include “print.hpp”
std::list coll;
std::front_insert_iterator
*iter = 1;
iter++;
*iter = 2;
iter++;
*iter = 3;
PRINT_ELEMENTS(coll);std::front_inserter(coll) = 44;
std::front_inserter(coll) = 55;
PRINT_ELEMENTS(coll);
std::copy(coll.begin(), coll.end(), std::front_inserter(coll));
PRINT_ELEMENTS(coll);
return 0;
3 2 1
55 44 3 2 1
1 2 3 44 55 55 44 3 2 1
#if 0 //iter /inserter1.cpp 2021年04月04日 星期日 07时31分33秒 p459
#include
#include
#include
#include
#include
#include “print.hpp”
std::set coll;
std::insert_iterator
*iter = 1;
iter++;
*iter = 2;
iter++;
*iter = 3;PRINT_ELEMENTS(coll, "set: ");
inserter(coll, coll.end()) = 44;
inserter(coll, coll.end()) = 55;
PRINT_ELEMENTS(coll, "set: ");
std::list
set: 1 2 3
list: 1 2 3
list: 1 1 2 3 2 3
#include
#include
#include
#include
std::ostream_iterator intWriter(std::cout,"\n");*intWriter = 42;
intWriter++;
*intWriter = 77;
intWriter++;
*intWriter = -5;
std::vector
42
77
-5
123456789
1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9 <
#include
#include
std::istream_iterator intReader(std::cin);
std::istream_iterator intReaderEOF;
while(intReader != intReaderEOF){
std::cout << "once: " << *intReader << std::endl;
std::cout << “once again:” << *intReader << std::endl;
++intReader;
}
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
1 2 3 f 4
once: 1
once again:1
once: 2
once again:2
once: 3
once again:3
#include
#include
#include
#include
std::istream_iteratorstd::string cinPos(std::cin);
std::ostream_iteratorstd::string coutPos(std::cout, " ");
while (cinPos != std::istream_iteratorstd::string()){
advance (cinPos, 2);
if(cinPos != std::istream_iteratorstd::string()){
*coutPos++ = *cinPos++;
}
}
std::cout << std::endl;
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
No one objects if you are doing a good programming job for someone whom you respect
objects are good for you
#include
#include
#include
#include
#include “print.hpp”
#include “assoiter.hpp”
std::unordered_set coll;
asso_insert_iterator
*iter = 1;
iter++;
*iter = 2;
iter++;
*iter = 3;
PRINT_ELEMENTS(coll);asso_inserter(coll) = 44;
asso_inserter(coll) = 55;
PRINT_ELEMENTS(coll);
std::vector
3 2 1
1 2 3 55 44
5 -4 67 1 13 2 3 33 55 44
#include
#include
#include
#include
class Person{
public:
std::string firstname() const;
std::string lastname() const;
};
public:
bool operator() (const Person& p1, const Person& p2) const{
return p1.lastname() < p2.lastname() ||
(p1.lastname() == p2.lastname() &&
p1.firstname() < p2.firstname());
}
};
std::set
for(auto pos = coll.begin(); pos != coll.end(); ++pos){}
return 0;
#endif
#include
#include
#include
#include
#include “print.hpp”
class IntSequence{
private:
int value;
public:
IntSequence(int initialValue): value(initialValue){ }
int operator() (){
return ++value;
}
};
std::list coll;
generate_n (std::back_inserter(coll), 9, IntSequence(1));
PRINT_ELEMENTS(coll);
generate_n (next(coll.begin()), prev(coll.end()), IntSequence(42));
PRINT_ELEMENTS(coll);
return 0;
}错误:no match for ‘operator+’ (operand types are ‘std::_List_iterator’ and ‘int’)
4497 | for (__decltype(__n + 0) __niter = __n;
#if 0 //p480 fo/sequence2.cpp 2021年04月04日 星期日 19时29分26秒
#include
#include
#include
#include
#include “print.hpp”
class IntSequence{
private: int value;
public:
IntSequence(int initialValue): value(initialValue){ }
int operator() (){
return ++value;
}
};
std::list coll;
IntSequence seq(1);
std::generate_n
int, IntSequence&>(std::back_inserter(coll), 4, seq);
//lost 4, 错误:cannot convert ‘IntSequence’ to ‘int’
// 3107 | nsert_iterator
// | ^~~
//IntSequence
PRINT_ELEMENTS(coll);std::generate_n(std::back_inserter(coll), 4, IntSequence(42));
PRINT_ELEMENTS(coll);
std::generate_n(std::back_inserter(coll), 4, seq);
PRINT_ELEMENTS(coll);
std::generate_n(std::back_inserter(coll), 4, seq);
PRINT_ELEMENTS(coll);
return 0;
2 3 4 5
2 3 4 5 43 44 45 46
2 3 4 5 43 44 45 46 6 7 8 9
2 3 4 5 43 44 45 46 6 7 8 9 6 7 8 9
#include
#include
#include
class MeanValue{
private:
long num;
long sum;
public:
MeanValue () : num(0), sum(0){ }
void operator()(int elem){
++num;
sum += elem;
}
double value(){
return static_cast(sum) / static_cast(num);
}
};
std::vector coll {1, 2, 3, 4, 5, 6, 7, 8};
MeanValue mv = std::for_each(coll.begin(), coll.end(),
MeanValue());
std::cout << "mean value: " << mv.value() << std::endl;
return 0;
}wannian07@wannian07-PC:~/Desktop/The Complete Reference$ ./hello
mean value: 4.5
#include
#include
#include
#include “print.hpp”
class Nth{
private:
int nth;
int count;
public:
Nth(int n): nth(n), count(0){ }
bool operator() (int){
return ++count == nth;
}
};
std::list coll {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
PRINT_ELEMENTS(coll, "coll: ");std::list
coll: 1 2 3 4 5 6 7 8 9 10
3rd removed: 1 2 4 5 7 8 9 10
#include
#include
auto plus10 = std::bind(std::plus(),
std::placeholders::_1, 10);
std::cout << "+10: " << plus10(7) << std::endl;
auto plus10times2 = std::bind(std::multiplies(),
std::bind(std::plus(), std::placeholders::_1, 10), 2);
std::cout << "+10 *2: " << plus10times2(7) << std::endl;auto pow3 = std::bind(std::multiplies
+10: 17
+10 2: 34
xx*x: 343
invdiv: 0.142857