Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  
 
 
Рейтинг 4.92/1010: Рейтинг темы: голосов - 1010, средняя оценка - 4.92
 Аватар для ZarinZomanu4
10 / 10 / 0
Регистрация: 27.05.2013
Сообщений: 92

Решение всех задач из учебника Стивена Праты

23.03.2015, 12:20. Показов 217196. Ответов 271
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте!Решил выложить свои решения задач книги С. Прата. Код ни в коем случае не претендует на звание эталонного, если есть замечания с радостью выслушаю и приму к сведению.

Глава 4

Задания




Задача №1
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
 
int main ()
{ 
    using namespace std;
    const int ArSize = 20;
    char Fname[ArSize];
    char Lname[ArSize];
    int age;
    char bit;
    //enum gradeW {A,B,C};
    cout<<"what is your first name "<<endl;
    cin.getline(Fname,ArSize);
    cout<<"what is your last name "<<endl;
    cin.getline(Lname,ArSize);
    cout<<"what letter grade do you deserve(A,B,C) "<<endl;
    cin>>bit;
    cout<<"what is your age "<<endl;
    cin>> age ;
    cin.get();
    cout<<"Name: "<<Lname<<" "<<Fname<<endl;
    cout<<"Age: "<<age<<endl;
    switch (bit)
        {case 'A':
            cout<<"Grade B "<<endl;
            break;
        case 'B':
            cout<<"Grade C"<<endl;
            break;
        case 'C':
            cout<<"Grade D"<<endl;
            break;
        default: cout<<"wrong"<<endl;}
    cin.get();
    return 0;
  }

Задача №2
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
int main ()
{ 
    using namespace std;
    string Fname;
    string Lname;
    int age;
    char bit;
    cout<<"what is your first name "<<endl;
    getline(cin,Fname);
    cout<<"what is your last name "<<endl;
    getline(cin,Lname);
    cout<<"what letter grade do you deserve(A,B,C) "<<endl;
    cin>>bit;
    cout<<"what is your age "<<endl;
    cin>> age ;
    cin.get();
    cout<<"Name: "<<Lname<<" "<<Fname<<endl;
    cout<<"Age: "<<age<<endl;
    switch (bit)
        {case 'A':
            cout<<"Grade B "<<endl;
            break;
        case 'B':
            cout<<"Grade C"<<endl;
            break;
        case 'C':
            cout<<"Grade D"<<endl;
            break;
        default: cout<<"dsfsfsfsfsd"<<endl;}
    cin.get();
    return 0;
  }

Задача №3
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
//#include <string>
int main ()
{ 
    using namespace std;
    const int ArSize = 20;
    char Fname[ArSize];
    char Lname[ArSize];
    cout<<"Enter your first name "<<endl;
    cin.getline(Fname,ArSize);
    cout<<"Enter your last name "<<endl;
    cin.getline(Lname,ArSize);
    cout<<"Name: "<<Lname<<",  "<<Fname<<endl;
    cin.get();
    return 0;
  }

Задача №5
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
struct CandyBar
    {
        char Name [20];
        double netto;
        int Ccal;
    };
int main ()
{ 
    using namespace std;
    CandyBar snack={"Mocha Much",2.3,350};
    cout<<"Struct )))) "<<snack.Name<<snack.netto<<"     "<<snack.Ccal<<endl;
    cin.get();
    return 0;
  }

Задача №6
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
struct CandyBar
    {
        char Name [20];
        double netto;
        int Ccal;
    };
int main ()
{ 
    using namespace std;
    CandyBar snack[3]={
        {"Mocha Much",2.3,350},
        {"sfdsfsdf",2.45,435},
        {"bnderlogi", 2.12 , 777}};
 
    cout<<"Struct  "<<snack[2].Name<<"    "<<snack[2].netto<<"   "<<snack[0].Ccal<<endl;
    cin.get();
    return 0;
  }

Задача №7
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
struct Pizza
    {
        char Name [20];
        double netto;
        int Ccal;
    };
int main ()
{   using namespace std;
    Pizza Peper;
    cout<<"Enter Name:"<<endl;
    cin.getline (Peper.Name,20);
    cout<<"Enter diametr:"<<endl;
    cin>>Peper.netto;
    cout<<"Enter ves:"<<endl;
    cin>>Peper.Ccal;
    cout<<"Pizza: "<<Peper.Name<<endl<<"Diametr: "<<Peper.netto<<endl<<"Ves: "<<Peper.Ccal<<endl;
    cin.get();
    cin.get();
    return 0;
  }

Задача №8
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
struct Pizza
{
    std :: string Name ;
    double netto;
    int Ccal;
    };
int main ()
{   using namespace std;
    Pizza *pz =new Pizza;
    cout<<"Enter diametr:"<<endl;
    cin>>(*pz).netto;
    cout<<"Enter Name:"<<endl;
    cin>>(*pz).Name ;
    cout<<"Enter ves:"<<endl;
    cin>>(*pz).Ccal;
    cout<<"Pizza: "<<(*pz).Name<<endl;
    cout<<"Diametr: "<<(*pz).netto<<endl<<"Ves: "<<(*pz).Ccal<<endl;
    system ("pause");
    delete pz;
    return 0;
  }

Задача №9
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
struct CandyBar
    {
        std::string Name  ;
        double netto;
        int Ccal;
    };
void main ()
{ 
    using namespace std;
    CandyBar *bar= new CandyBar[3];
    bar[0].Name="Mocha Much";
    bar[0].netto=2.3;
    bar[0].Ccal=350;
    bar[1].Name="sfdsfsdf";
    bar[1].netto=2.45;
    bar[1].Ccal=435;
    bar[2].Name="bnderlogi";
    bar[2].netto=2.12;
    bar[2].Ccal=777;
    cout<<"Struct  "<<bar[0].Name<<"    "<<bar[0].netto<<"   "<<bar[0].Ccal<<endl;
    system("pause");
    delete bar;
          }

Задача №10
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
int main ()
{ 
    using namespace std;
    int bar[3];
    cout<<"Vvedite rezyltat 1 "<<endl;
    cin>>bar[0];
    cout<<"Vvedite rezyltat 2 "<<endl;
    cin>>bar[1];
    cout<<"Vvedite rezyltat 3 "<<endl;
    cin>>bar[2];
    int Sr=(bar[0]+bar[1]+bar[2])/3;
    cout<<"Rezyltat  "<<bar[0]<<"    "<<bar[1]<<"   "<<bar[2]<<"  Srednee "<<Sr<<endl;
    system("pause");
}


Задачи из глав с 4 о 10, решенные sourcerer
9
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
23.03.2015, 12:20
Ответы с готовыми решениями:

Нюансы синтаксиса: классы, список инициализации (неясная строка из учебника Стивена Праты)
Вот сам класс #ifndef TABTENN0_H_ #define TABTENN0_H_ #include &lt;string&gt; using std :: string; class...

читаю главу 10 книги стивена праты - "объекты и классы". автор во всех примерах поступает следуйщим образм: объявляет класс в одном фаиле...
...а реализует функции в другом - в том котором создаёт и ползуется объектом. у меня вопросс: а не лучше ли (практичнее, или возможно ли...

Неожиданный консольный вывод (упражнения 3 к главе 6 книги Стивена Праты)
:-| Вообщем имеется код (решение 3 упражнения к главе 6 книги Прата): #include &lt;iostream&gt; #include&lt;cstdlib&gt; ...

271
0 / 0 / 0
Регистрация: 29.07.2020
Сообщений: 4
16.02.2023, 22:53
Студворк — интернет-сервис помощи студентам
Цитата Сообщение от SmallEvil Посмотреть сообщение
Можете озвучить эту задачу тут ?
Необходимо найти количество клиентов банкомата за час, которое приводит к среднему времени ожидания равному одной минуте с помощью модели из книги. Применять по меньшей мере 100-часовой период моделирования.
Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// queue.h -- interface for a queue
#ifndef QUEUE_H_
#define QUEUE_H_
// This queue will contain Customer items
class Customer
{
private:
    long arrive;        // arrival time for customer
    int processtime;    // processing time for customer
public:
    Customer() : arrive(0), processtime (0){}
    void set(long when);
    long when() const { return arrive; }
    int ptime() const { return processtime; }
};
 
typedef Customer Item;
 
class Queue
{
private:
// class scope definitions
    // Node is a nested structure definition local to this class
    struct Node { Item item; struct Node * next;};
    enum {Q_SIZE = 10};
// private class members
    Node * front;       // pointer to front of Queue
    Node * rear;        // pointer to rear of Queue
    int items;          // current number of items in Queue
    const int qsize;    // maximum number of items in Queue
    // preemptive definitions to prevent public copying
    Queue(const Queue & q) : qsize(0) { }
    Queue & operator=(const Queue & q) { return *this;}
public:
    Queue(int qs = Q_SIZE); // create queue with a qs limit
    ~Queue();
    bool isempty() const;
    bool isfull() const;
    int queuecount() const;
    bool enqueue(const Item &item); // add item to end
    bool dequeue(Item &item);       // remove item from front
};
#endif


Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// queue.cpp -- Queue and Customer methods
#include "queue.h"
#include <cstdlib>         // (or stdlib.h) for rand()
 
// Queue methods
Queue::Queue(int qs) : qsize(qs)
{
    front = rear = NULL;    // or nullptr
    items = 0;
}
 
Queue::~Queue()
{
    Node * temp;
    while (front != NULL)   // while queue is not yet empty
    {
        temp = front;       // save address of front item
        front = front->next;// reset pointer to next item
        delete temp;        // delete former front
    }
}
 
bool Queue::isempty() const
{
    return items == 0;
}
 
bool Queue::isfull() const
{
    return items == qsize;
}
 
int Queue::queuecount() const
{
    return items;
}
 
// Add item to queue
bool Queue::enqueue(const Item & item)
{
    if (isfull())
        return false;
    Node * add = new Node;  // create node
// on failure, new throws std::bad_alloc exception
    add->item = item;       // set node pointers
    add->next = NULL;       // or nullptr;
    items++;
    if (front == NULL)      // if queue is empty,
        front = add;        // place item at front
    else
        rear->next = add;   // else place at rear
    rear = add;             // have rear point to new node
    return true;
}
 
// Place front item into item variable and remove from queue
bool Queue::dequeue(Item & item)
{
    if (front == NULL)
        return false;
    item = front->item;     // set item to first item in queue
    items--;
    Node * temp = front;    // save location of first item
    front = front->next;    // reset front to next item
    delete temp;            // delete former first item
    if (items == 0)
        rear = NULL;
    return true;
}
 
// customer method
 
// when is the time at which the customer arrives
// the arrival time is set to when and the processing
// time set to a random value in the range 1 - 3
void Customer::set(long when)
{
    processtime = std::rand() % 3 + 1;
    arrive = when; 
}


Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// bank.cpp -- using the Queue interface
// compile with queue.cpp
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime>   // for time()
#include "queue.h"
const int MIN_PER_HR = 60;
 
bool newcustomer(double x); // is there a new customer?
 
int main()
{
    using std::cin;
    using std::cout;
    using std::endl;
    using std::ios_base;
// setting things up
    std::srand(std::time(0));    //  random initializing of rand()
 
    cout << "Case Study: Bank of Heather Automatic Teller\n";
    cout << "Enter maximum size of queue: ";
    int qs;
    cin >> qs;
    Queue line(qs);         // line queue holds up to qs people
 
    cout << "Enter the number of simulation hours: ";
    int hours;              //  hours of simulation
    cin >> hours;
    // simulation will run 1 cycle per minute
    long cyclelimit = MIN_PER_HR * hours; // # of cycles
 
    cout << "Enter the average number of customers per hour: ";
    double perhour;         //  average # of arrival per hour
    cin >> perhour;
    double min_per_cust;    //  average time between arrivals
    min_per_cust = MIN_PER_HR / perhour;
 
    Item temp;              //  new customer data
    long turnaways = 0;     //  turned away by full queue
    long customers = 0;     //  joined the queue
    long served = 0;        //  served during the simulation
    long sum_line = 0;      //  cumulative line length
    int wait_time = 0;      //  time until autoteller is free
    long line_wait = 0;     //  cumulative time in line
 
 
// running the simulation
    for (int cycle = 0; cycle < cyclelimit; cycle++)
    {
        if (newcustomer(min_per_cust))  // have newcomer
        {
            if (line.isfull())
                turnaways++;
            else
            {
                customers++;
                temp.set(cycle);    // cycle = time of arrival
                line.enqueue(temp); // add newcomer to line
            }
        }
        if (wait_time <= 0 && !line.isempty())
        {
            line.dequeue (temp);      // attend next customer
            wait_time = temp.ptime(); // for wait_time minutes
            line_wait += cycle - temp.when();
            served++;
        }
        if (wait_time > 0)
            wait_time--;
        sum_line += line.queuecount();
    }
 
// reporting results
    if (customers > 0)
    {
        cout << "customers accepted: " << customers << endl;
        cout << "  customers served: " << served << endl;
        cout << "         turnaways: " << turnaways << endl;
        cout << "average queue size: ";
        cout.precision(2);
        cout.setf(ios_base::fixed, ios_base::floatfield);
        cout << (double) sum_line / cyclelimit << endl;
        cout << " average wait time: "
             << (double) line_wait / served << " minutes\n";
    }
    else
        cout << "No customers!\n";
    cout << "Done!\n";
    // cin.get();
    // cin.get();
    return 0;
}
 
//  x = average time, in minutes, between customers
//  return value is true if customer shows up this minute
bool newcustomer(double x)
{
    return (std::rand() * x / RAND_MAX < 1); 
}
0
0 / 0 / 0
Регистрация: 18.07.2021
Сообщений: 12
22.03.2023, 14:34
Глава 12. Задача 2

Файл 1 (хэдэр)
Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// string1.h -- fixed and augmented string class definition
 
#ifndef STRING1_H_
#define STRING1_H_
#include <iostream>
using std::ostream;
using std::istream;
 
class String
{
private:
    char * str;             // pointer to string
    int len;                // length of string
    static int num_strings; // number of objects
    static const int CINLIM = 80;  // cin input limit
public:
// constructors and other methods
    String(const char * s); // constructor
    String();               // default constructor
    String(const String &); // copy constructor
    ~String();              // destructor
    int length () const { return len; }
// overloaded operator methods    
    String & operator=(const String &);
    String & operator=(const char *);
    char & operator[](int i);
    const char & operator[](int i) const;
    String operator+(const String& rb) const;
    void stringlow();
    void stringup();
    int has(char ch) const;
// overloaded operator friends
    friend bool operator<(const String &st, const String &st2);
    friend bool operator>(const String &st1, const String &st2);
    friend bool operator==(const String &st, const String &st2);
    friend ostream & operator<<(ostream & os, const String & st);
    friend istream & operator>>(istream & is, String & st);
    friend String operator+(const char* ch, const String& rb);
// static function
    static int HowMany();
};
#endif

Файл 2 (определения)
Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
// string1.cpp -- String class methods
//#include <cstring>                 // string.h for some
#include "string1.h"               // includes <iostream>
#include <cctype>
using std::cin;
using std::cout;
 
// initializing static class member
 
int String::num_strings = 0;
 
// static method
int String::HowMany()
{
    return num_strings;
}
 
// class methods
String::String(const char * s)     // construct String from C string
{
    len = std::strlen(s);          // set size
    str = new char[len + 1];       // allot storage
    strcpy_s(str, len + 1, s);           // initialize pointer
    num_strings++;                 // set object count
}
 
String::String()                   // default constructor
{
    len = 4;
    str = new char[1];
    str[0] = '\0';                 // default string
    num_strings++;
}
 
String::String(const String & st)
{
    num_strings++;             // handle static member update
    len = st.len;              // same length
    str = new char [len + 1];  // allot space
    strcpy_s(str, len + 1, st.str);  // copy string to new location
}
 
String::~String()                     // necessary destructor
{
    --num_strings;                    // required
    delete [] str;                    // required
}
 
// overloaded operator methods    
 
    // assign a String to a String
int String::has(char ch) const
{
    int ac = 0;
    for (int i = 0; *(str + i) != '\0'; i++)
    {
        if (*(str + i) == ch)
            ++ac;
    }
    return ac;
}
 
void String::stringup()
{
    for (int i = 0; *(str + i) != '\0'; i++)
    {
        *(str + i) = toupper(*(str + i));
    }
}
 
void String::stringlow()
{
    for (int i = 0; *(str + i) != '\0'; i++)
    {
        *(str + i) = tolower(*(str + i));
    }
}
 
String operator+(const char* ch, const String& rb)
{
    int cch = strlen(ch);
    char* buff = new char[cch + rb.len + 1];
    for (int i = 0; i < cch; i++)
    {
        *(buff + i) = *(ch + i);
    }
    for (int i = 0; i < rb.len; i++)
    {
        *(buff + cch + i) = *(rb.str + i);
    }
    *(buff + cch + rb.len) = '\0';
 
    String temp(buff);
    delete[] buff;
    return temp;
}
 
String String::operator+(const String& rb) const
{
    char* buff = new char[this->len + rb.len + 1];
    for (int i = 0; i < this->len; i++)
    {
        *(buff + i) = *(this->str + i);
    }
    for (int i = 0; i < rb.len; i++)
    {
        *(buff + this->len + i) = *(rb.str + i);
    }
    *(buff + this->len + rb.len) = '\0';
 
    String temp(buff);
    delete[] buff;
    return temp;
}
 
String & String::operator=(const String & st)
{
    if (this == &st)
        return *this;
    delete [] str;
    len = st.len;
    str = new char[len + 1];
    strcpy_s(str, len + 1, st.str);
    return *this;
}
 
    // assign a C string to a String
String & String::operator=(const char * s)
{
    delete [] str;
    len = std::strlen(s);
    str = new char[len + 1];
    strcpy_s(str, len + 1, s);
    return *this;
}
 
    // read-write char access for non-const String
char & String::operator[](int i)
{
    return str[i];
}
 
    // read-only char access for const String
const char & String::operator[](int i) const
{
    return str[i];
}
 
// overloaded operator friends
 
bool operator<(const String &st1, const String &st2)
{
    return (std::strcmp(st1.str, st2.str) < 0);
}
 
bool operator>(const String &st1, const String &st2)
{
    return st2 < st1;
}
 
bool operator==(const String &st1, const String &st2)
{
    return (std::strcmp(st1.str, st2.str) == 0);
}
 
    // simple String output
ostream & operator<<(ostream & os, const String & st)
{
    os << st.str;
    return os; 
}
 
    // quick and dirty String input
istream & operator>>(istream & is, String & st)
{
    char temp[String::CINLIM];
    is.get(temp, String::CINLIM);
    if (is)
        st = temp;
    while (is && is.get() != '\n')
        continue;
    return is; 
}

Файл 3 (мэйн)
Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <string>
#include "string1.h"
 
using namespace std;
 
int main()
{
    String s1(" and I am a C++ student.");
    String s2 = "Pleace enter your name: ";
    String s3;
    cout << s2;
    cin >> s3;
    s2 = "My name is " + s3;
    cout << s2 << ".\n";
    s2 = s2 + s1;
    s2.stringup();
    cout << "The string\n" << s2 << "\ncontains " << s2.has('A')
        << " 'A' characters in it.\n";
    s1 = "red";
 
    String rgb[3] = { String(s1), String("green"), String("blue") };
    cout << "Enter the name of a primary color for mixing light: ";
    String ans;
    bool success = false;
    while (cin >> ans)
    {
        ans.stringlow();
        for (int i = 0; i < 3; i++)
        {
            if (ans == rgb[i])
            {
                cout << "That's right!\n";
                success = true;
                break;
            }
        }
        if (success)
            break;
        else
            cout << "Tru again!\n";
    }
    cout << "Bye\n";
    
 
    cin.get();
    cin.get();
    return 0;
}
0
0 / 0 / 0
Регистрация: 11.03.2023
Сообщений: 7
23.03.2023, 14:45
Огромное спасибо товарищ Dutch! Полдня голову ломал как в конструкторе присвоить ссылку объекта ofstream в задаче 7 17 главы
0
 Аватар для AmbA
495 / 24 / 6
Регистрация: 09.06.2017
Сообщений: 322
Записей в блоге: 21
14.04.2023, 13:53
Глава 8, задача 6.
Так и не смог заставить выдать мне указатель на char в виде адреса, а не в виде строки. Пришлось схитрить. Очень хотелось бы увидеть правильное решение.
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Ex_8.6.cpp
/*Напишите шаблонную функцию maxn() , которая принимает в качестве аргумента массив элементов типа т и целое число, представляющее количество элементов в массиве, а возвращает элемент с наибольшим значением. Протестируйте ее работу в программе, которая использует этот шаблон с массивом из шести значений int и массивом из четырех значений double .
Программа также должна включать специализацию, которая использует массив указателей на char в качестве первого аргумента и количество указателей - в качестве второго , а затем возвращает адрес самой длинной строки. Если имеется более одной строки наибольшей длины, функция должна вернуть адрес первой из них. Протестируйте специализацию на массиве из пяти указателей на строки*/
 
#include <iostream>
 
template<typename T>
int maxn(T arrN[], int n)
{
    int num {0};
    T temp = arrN[num];
    for (int i {1}; i < n; ++i)
        if (temp < arrN[i])
        {
            temp = arrN[i];
            num = i;
        }
    return num;
}
 
int maxn(const char *arr[], int n)
{
    int num {0};
    int temp = strlen(arr[num]);
    for(int i {1}; i < n; ++i)
        if(temp < strlen(arr[i]))
        {
            temp = strlen(arr[i]);
            num = i;
        }
    return num;
}
 
int main()
{
    using namespace std;
    int arrI[6] {5, 4, 6, 7, 3, 2};
    double arrD[4] {6.6, 5.5, 8.8, 7.7};
    
    const char *arrC[3]
    {
        "1oooooo", "2iiii", "3uuuuuu"
    };
    cout << maxn(arrI, 6) << endl;
    cout << maxn(arrD, 4) << endl;
    cout << &arrC[maxn(arrC, 3)];
    return 0;
}
0
Just Do It!
 Аватар для XLAT
4219 / 2680 / 656
Регистрация: 23.09.2014
Сообщений: 9,235
Записей в блоге: 3
14.04.2023, 14:32
Цитата Сообщение от AmbA Посмотреть сообщение
Очень хотелось бы увидеть правильное решение.
C++
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <vector>
#include <algorithm>
 
int main()
{
    std::vector<char> v = {2, 1, 3, 6, 7, 9, 8};
 
    int max = *std::max_element(v.begin(), v.end());
 
    std::cout << "max: " << max << std::endl;
}
https://rextester.com/QUAI80473
0
118 / 86 / 35
Регистрация: 07.11.2022
Сообщений: 355
14.04.2023, 17:56
Цитата Сообщение от AmbA Посмотреть сообщение
хотелось бы увидеть правильное решение.
давайте так

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
template<class T>
T maxn(T arr[], std::size_t n)
{
    T max_val  {};
    for (std::size_t i= 0 ; i < n ; i++)
    {
        if (arr[i] > max_val)
        {
            max_val = arr[i];
        }
    }
    return max_val;
}
 
template<>
const char * maxn(const char * arr[], std::size_t n)
{
    std::size_t max_len = 0, max_ind = 0;
    for (std::size_t i= 0 ; i < n ; i++)
    {
        std::size_t cur_len = strlen(arr[i]);
        if (cur_len > max_len)
        {
            max_len = cur_len;
            max_ind = i;
        }
    }
    return arr[max_ind];
}
 
 
 
int main()
{
    const std::size_t LEN_I  = 6;
    const std::size_t LEN_D  = 4;
    const std::size_t LEN_CHAR_PTR  = 3;
    
    int arrI[LEN_I] {5, 4, 6, 7, 3, 2};    
    double arrD[LEN_D] {6.6, 5.5, 8.8, 7.7};
    const char *arrC[LEN_CHAR_PTR]
    {
        "aaaaa", "bbbb", "ttt"
    };
    
    std::cout << maxn(arrI, LEN_I) <<   std::endl;
    std::cout << maxn(arrD, LEN_D) <<   std::endl;
    std::cout << maxn(arrC, LEN_CHAR_PTR)<<   std::endl;
    return 0;
}

Цитата Сообщение от AmbA Посмотреть сообщение
выдать мне указатель на char в виде адреса, а не в виде строки
не знаю зачем это нужно .
получить адрес

C++
1
2
3
   
  const char* s = ...
  std::uintptr_t ptr = reinterpret_cast<std::uintptr_t>( s);
0
 Аватар для AmbA
495 / 24 / 6
Регистрация: 09.06.2017
Сообщений: 322
Записей в блоге: 21
15.04.2023, 01:54
Цитата Сообщение от XLAT Посмотреть сообщение
https://rextester.com/QUAI80473
Показывает больший элемент массива, а нужен его адрес.
Цитата Сообщение от NEED-A-JOB Посмотреть сообщение
давайте так
Аналогично.
Цитата Сообщение от NEED-A-JOB Посмотреть сообщение
не знаю зачем это нужно .
Задача такая )
Цитата Сообщение от NEED-A-JOB Посмотреть сообщение
получить адрес
В последней строчке большая часть мне незнакома. Мы проходили: создать указатель/разыменовать указатель, создать ссылку, получить адрес.
И вроде бы этих средств должно быть достаточно
О.
Стал отвечать, и решил ))
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Ex_8.6.cpp
 
#include <iostream>
 
template<typename T>
int maxn(T arrN[], int n)
{
  int num {0};
  T temp = arrN[num];
  for(int i {1}; i < n; ++i)
    if(temp < arrN[i])
    {
      temp = arrN[i];
      num = i;
    }
  return num;
}
 
const char **maxn(const char *arr[], int n)
{
  int num {0};
  int temp = strlen(arr[num]);
  for(int i {1}; i < n; ++i)
    if(temp < strlen(arr[i]))
    {
      temp = strlen(arr[i]);
      num = i;
    }
  return &arr[num];
}
 
int main()
{
  using namespace std;
  int arrI[6] {5, 4, 6, 7, 3, 2};
  double arrD[4] {6.6, 5.5, 8.8, 7.7};
 
  const char *arrC[3]
  {
    "1oooooo", "2iiii", "3uuuuuu"
  };
  cout << maxn(arrI, 6) << endl;
  cout << maxn(arrD, 4) << endl;
  cout << maxn(arrC, 3) << endl;
  return 0;
}
Code
1
2
3
3
2
0000006F126FF518
0
118 / 86 / 35
Регистрация: 07.11.2022
Сообщений: 355
15.04.2023, 04:05
Цитата Сообщение от AmbA Посмотреть сообщение
решил ))
вы получили индексы элементов
Цитата Сообщение от AmbA Посмотреть сообщение
Code
1
2
3
2
а нужно вернуть элементы с наибольшим значением.
Цитата Сообщение от AmbA Посмотреть сообщение
Напишите шаблонную функцию maxn() , которая .... возвращает элемент с наибольшим значением.
Элемент с наибольшим значением
здесь
C++
1
int arrI[6] {5, 4, 6, 7, 3, 2};
это 7, а не 3 как у вас.
0
 Аватар для AmbA
495 / 24 / 6
Регистрация: 09.06.2017
Сообщений: 322
Записей в блоге: 21
15.04.2023, 05:53
Ну, я понял иначе.
"наибольшее значение" - 7
"элемент с наибольшим значением" - его индекс, 3
0
Just Do It!
 Аватар для XLAT
4219 / 2680 / 656
Регистрация: 23.09.2014
Сообщений: 9,235
Записей в блоге: 3
15.04.2023, 10:29
Цитата Сообщение от AmbA Посмотреть сообщение
а нужен его адрес.
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <vector>
#include <algorithm>
 
int main()
{
    std::vector<char> v = {2, 1, 3, 6, 7, 9, 8};
 
    char& max = *std::max_element(v.begin(), v.end()); 
    
    std::cout << "value max: " << (int)max << std::endl;
    
    int* adress = (int*)&max;
    
    std::cout << "adress   : " << adress << std::endl;
    
    *adress = 42;
    
    std::cout << "value max: " << (int)max << std::endl;
    
    std::cout << "index max: " << std::max_element(v.begin(), v.end()) - v.begin() << std::endl;
}
0
0 / 0 / 0
Регистрация: 16.05.2022
Сообщений: 16
20.04.2023, 15:54
Всем доброго времени суток. Продолжаю прорешивать задания по книге столкнулся с проблемой в 14-й главе а именно, как правильно перегрузить оператор= в моем случае:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#ifndef WINE_H_
#define WINE_H_
#include<iostream>
#include<valarray>
template<class T1,class T2>
class Pair
{
private:
    T1 a; //valarray<int> a
    T2 b;
public:
    Pair(){}
    T1 &first();
    T2 &second();
    T1 first()const{return a;}
    T2 second()const{return b;}
    Pair(const T1 &a,const T2 &b):a(a),b(b){}
    T1 &operator=(const &Pair pa)
};
template<class T1,class T2>
T1 &Pair<T1,T2>::first()
{
    return a;
}
template<class T1,class T2>
T2 &Pair<T1,T2>::second()
{
    return b;
}
template<class T1,class T2>
T1 &Pair<T1,T2>::operator=(const &Pair pa)
{
 
}
typedef std::valarray<int> ArrayInt;
typedef Pair<ArrayInt,ArrayInt> PairArray;
14 глава 2 задание закрытое множественное наследование. Автор просит подумать как можно применить данный код:
C++
1
2
3
4
PairArray::operator=(PairArray(ArrayInt(),ArrayInt()))
{
    
}
Пол дня пытаюсь перегрузить оператор = не получается.
0
0 / 0 / 0
Регистрация: 16.05.2022
Сообщений: 16
21.04.2023, 09:36
Нашел решение данного вопроса:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
template<class T1,class T2>
class Pair
{
private:
    T1 a; //valarray<int> a
    T2 b;
public:
    Pair(){}
    T1 &first();
    T2 &second();
    T1 first()const{return a;}
    T2 second()const{return b;}
    Pair(const T1 &a,const T2 &b):a(a),b(b){}
    Pair<T1,T2> &operator=(const Pair<T1,T2> &pa);
};
template<class T1,class T2>
Pair<T1,T2> &Pair<T1,T2>::operator=(const Pair<T1,T2> &pa)
{
    if (this==&pa)return *this;
    this->a=pa.a;
    this->b=pa.b;
    return *this; 
}
0
1 / 1 / 0
Регистрация: 13.06.2019
Сообщений: 34
22.08.2023, 15:09
sourcerer, sourcerer,
Добрый день

Вы не могли бы упрастить решение задачи 10 из 5 главы книги Стива Плата

Суть проблемы в том что там функция, а она рассматривается только в
7 главе.

Например вот на такое решение, по теме главы

Спасибо

/*Напишите программу, использующую вложенные циклы, которая запрашивает у пользователя значение количества строк для отображения. Затем она должна отобразить указанное число строк со звездочками, с одной звездочкой в первой строке, двумя — во второй и т.д: В каждой строке звездочкам должны предшествовать точки — в таком количестве, чтобы общее число символов в каждой строке было равно количеству строк. Пример запуска программы должен выглядеть следующим образом: Введите количество строк: 5

. . . . *
. . . * *
. . * * *
. * * * *
* * * * *
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
*/
#include<iostream>
using namespace std;
 
int main(int argc, char *argv[])
{
 setlocale(0, "");
 int line;
 char star = '*';
 char dot = '.';
 
 cout << "Введите количество строк: ";
 cin>>line; 
 for(int i = 1; i < line; ++i)
 {
     for(int j = line; j != 0; --j)
     {
         if(j<=i)
             cout << star<<" ";
         else
             cout << dot <<" ";
     }
     cout <<endl;
 }
 return 0;
}
0
Модератор
Эксперт CЭксперт С++
 Аватар для sourcerer
5288 / 2376 / 342
Регистрация: 20.02.2013
Сообщений: 5,773
Записей в блоге: 20
23.08.2023, 21:03
Lord-Stanly, добрый. А зачем мне это делать, если это уже сделали Вы?

Добавлено через 26 минут
Lord-Stanly, подумал, пересилил лень, решил всё-таки сделать. Благо, делов на пять минут. Кстати, Ваше решение не удовлетворяет условию задачи. И да, инструкции ветвления if-else будут только в шестой главе, если уж на то пошло. Так что, вот так:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
 
int main()
{
    std::cout << "Please enter number of lines: ";
    int number_of_lines;
    std::cin >> number_of_lines;
    for (int x = 1; x <= number_of_lines; ++x)
    {
        for (int i = number_of_lines - x; i > 0; --i)
        {
            std::cout << '.';
        }
        for (int j = number_of_lines - x; j < number_of_lines; ++j)
        {
            std::cout << '*';
        }
        std::cout << '\n';
    }
}
1
1 / 1 / 0
Регистрация: 13.06.2019
Сообщений: 34
23.08.2023, 22:41
Да согласен

С if else забежал вперёд

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
using namespace std;
 
int main(int argc, char *argv[])
{
    setlocale(0, "");
    int line;
    char star = '*';
    char dot = '.';
    
    cout << "Введите количество строк: ";
    cin>>line; 
    for(int i = 1; i <line; i++)
    {
        for(int j = 0; j<line-i;++j)
            cout <<dot<<" ";
          
        for(int k = line - i; k < line; ++k)
                cout <<star<<" ";
        
        cout <<endl;
    }
    return 0;
}
У меня вот так получилось, суть впринцепе та же что и у вас.
1
Модератор
Эксперт CЭксперт С++
 Аватар для sourcerer
5288 / 2376 / 342
Регистрация: 20.02.2013
Сообщений: 5,773
Записей в блоге: 20
27.09.2023, 07:43
Цитата Сообщение от rat0r Посмотреть сообщение
можно пример?
Скорее всего, у меня там был выставлен флаг "-Wmissing-declarations"
0
Just Do It!
 Аватар для XLAT
4219 / 2680 / 656
Регистрация: 23.09.2014
Сообщений: 9,235
Записей в блоге: 3
27.09.2023, 11:55
Цитата Сообщение от Lord-Stanly Посмотреть сообщение
Вы не могли бы упрастить решение
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string>
#include <iostream>
 
int main()
{
    const char star = '*';
    const char dot  = '.';
 
    size_t line; std::cin >> line; std::string s(line, dot);
 
    while(--line < s.size())
    {   std::cout << (s[line] = star, s) << '\n';
    }
}
https://rextester.com/WRYC65128
1
1 / 1 / 0
Регистрация: 13.06.2019
Сообщений: 34
04.01.2024, 12:12
Добрый день

Не пойму ни как

Тут же должна быть специализация на char* восьмая глава задача 6

А тут обычная функция перегруженная.

И функция должна возвращать адрес, а не значение.

Есть у кого верное решение второй части задачи ?
0
19501 / 10106 / 2461
Регистрация: 30.01.2014
Сообщений: 17,825
04.01.2024, 12:56
Lord-Stanly, пост 246.
0
1 / 1 / 0
Регистрация: 13.06.2019
Сообщений: 34
04.01.2024, 13:36
К сожелению там нет правильного ответа, специализации нет, только перегруженная функция

Специализация должна быть

template<>
Const char* maxn<char>( const char* a[], int);

Но там такого нет

Помогите решить 6 задачу 8 главы!?
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
04.01.2024, 13:36

Найти причины и способы исправления ошибок в коде (упражнения по книге Стивена Праты)
В общем так . Пробую учить плюсы по книжке Прата . Пробую недавно , и потому полный нуб. От того и нумбский вопрос . В книжке написано что...

Задача из лекций по книге Стивена Праты
Глава 6 задача 5 Напишите программу, которая предлагает пользователю ввести прописную букву. Воспользуйтесь вложенными циклами, чтобы...

Решение задач из учебника Томшина
Я являюсь студентом 1-го курса, и нам дали задачи по c# которые необходимо решить. Задачи взяты из учебника Томшина , который предназначен...

Понятен материал учебника, но не получается самостоятельное решение задач
Здравствуйте. Читаю книжку Дейтелов, переписываю код, который дан в учебнике, потом читаю пояснения к строкам и в общем-то всё понимаю,...

Запишите в файл 2 название команды, количество решенных задач и общее времени, потраченное на решение всех задач
Подскажите как доделать задачу. В файле 1 хранятся данные о названиях команды, номере решенной задачи, времени, потраченном на решение....


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
260
Ответ Создать тему
Новые блоги и статьи
Эксперимент с картинкой-обложкой на CodinGame
Adler 10.07.2026
Решил на днях провести эксперимент. У меня есть аккаунт на CodinGame, ТОП-3 по РФ среди 2200 участников (в разделе соревнования по программированию ИИ-ботов). Там есть обложка, куда можно влепить. . .
После бана на Пикабу не работает авторизация аккаунта с Яндекса.
Hrethgir 09.07.2026
В частности https:/ / auto. ru/ logbook/ zapret-na-vozhdenie-posle-65-let_1cf28789-07b4-4c75-a2f7-4cd4edf9deeb тут хотел оставить комментарий такой Зрите в корень - монополизация на разработку программ. . .
GitDOS: Когда я решил скрестить MS-DOS, GitHub и Claude
MaGz GoLd 08.07.2026
Привет, Киберфорум! Хочу поделиться своим проектом, который, надеюсь, вас заинтересует. GitDOS — это веб-приложение, которое позволяет запускать DOS в браузере с тремя крутыми фичами: диски живут в. . .
Учебный мини "цифровой двойник" = (Сервер = Java + Flask_питон )+(3D = Гугловскаая 4T nvideo + google colab) +( WMS = Odoo на Docker)
anaschu 07.07.2026
Увидел в требованиях к вакансии создателя имитационных моделей связку (REst + Api + WMS + Anylogic + питон + 3D Nvideo), и решил посмотреть, что это такое. Из этого всего я работал более менее. . .
Море в объективе
kumehtar 06.07.2026
Хотел написать много проникновенных слов, но передумал. Оно само - говорит. Кто слышит тот слышит.
Doom для терминала без стрельбы и монстров. 3D Raycasting на ascii.
dcc0 05.07.2026
Попросил нейронную сеть deepai. org написать рейкастинг 3D с библиотекой ncurses для Linux. Чтобы можно было ходить на стрелочки. Чтобы стены были отрисованы символами. Справилась. Первый вариант. . .
Установка статуса документа по условию
Maks 05.07.2026
Алгоритм из решения ниже реализован на нетиповом документе "НарядПутевка" разработанного в КА2. Задача: в табличной части "Материалы" документа при записи автоматически устанавливать статус. . .
Сезонность и суточность закисления почв
anaschu 04.07.2026
200 часов это все равно моловато. Есть ситуации, но нестандартные, когда смена происходит за 5 лет. Но обычно это 50 лет и более. Наверное, закисление почвы происходит сезонно в средней. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru