|
|
|
2856 7 0 0 |
|
Опции темы | Поиск в этой теме |
04.06.2012, 19:32 | 1 |
Увлеченный
|
помогите с c++
уважаемые товарищи, кто хорошо знает плюсы? помогите мне переделать программку (сорцы в приложении). суть в том, что из 3-х линейных списков надо сделать один кольцевой, но так, чтобы доступ к данным остался прежним. Т.е, последняя запись первого списка должна указывать, на начало второго списка, конец второго списка должен указывать на начало третьего, а конец третьего - на начало первого. Это можно сделать уже после создания трех списков. То есть NULL в конце заменить на адрес начала следующего списка. И чтобы знать, где какой начинается и когда он кончается, нужны три указателя на начала разделов кольцевого списка. Вобщем принцип знаю, сделать не получается. Эта программа-то мне с трудом далась
|
04.06.2012, 22:24 | 2 |
Увлеченный
Регистрация: 22.05.2012 Последняя активность: 02.12.2015 21:10
Сообщений: 96
Сказал(а) спасибо: 0
Поблагодарили: 0 раз(а) в 0 сообщениях
|
Did you write 1.cpp?
There are some weird constructs in this code! void add(mixlist* &s, int k) What is s? A pointer to a reference? What? Вы написали 1.cpp? Некоторые конструкции весьма странные в нем! void add(mixlist* &s, int k) Что это? Указатель на ссылку? Или что? James.
__________________
Creator of LaserBoy! |
05.06.2012, 07:00 | 3 |
Увлеченный
|
Цитата:
Да, это я написал. Естественно, это указатель на ссылку. Программа работает хорошо. Мне необходимо переделать этот список в кольцевой, но я не знаю, как это сделать. |
05.06.2012, 07:47 | 4 |
Увлеченный
Регистрация: 22.05.2012 Последняя активность: 02.12.2015 21:10
Сообщений: 96
Сказал(а) спасибо: 0
Поблагодарили: 0 раз(а) в 0 сообщениях
|
A pointer to a reference makes no sense. I have never seen that before!
In a function argument list, you might have (type* x). That is a pointer to type x. It is a copy of a memory location that points to x. You might also have (type &x). This is a reference to x. It is actually the real value of x at its original memory location ~ not a copy. One you get x inside of the body of the function, you can take its address if you need it. If you want to make a circular list, you just need to link the last element of the list to the first! All of your lists are of the same type. Each one has an int data element and a pointer to its own type to point to another list element. You could add another data element to your list struct to identify which list it is by number, 1, 2 or 3. then you would know even after you linked them all together end to end, what element came from what list. struct list { int x; int list_id; list* next; }; Once the lists were populated, none of the lists would be NULL terminated. Every next pointer would point to something valid. The end of one list and the beginning of another would be designated by the fact that the list_id would change. Указатель на ссылку не имеет смысла. Я никогда не видел такой конструкции раньше! В аргументах функции вы можете использовать (type* x). Это указатель на х. Это копия адреса памяти, который указывает на значение x. Вы также можете использовать (type &x). Это ссылка на x. Вообще, это настоящее значение x по его актуальному адресу в памяти ~ не копия. Когда вы используете значение x внутри функции, вы можете узнать его адреса в памяти, если вам это необходимо. Если вы хотите создать круговой список, вам всего лишь необходимо замкнуть последний элемент списка на первый! Все ваши списки одного типа. Каждый элемент имеет целочисленную переменную и указатель собственного типа, который указывает на следующий элемент списка. Вы можете добавить еще одну переменную к элементам списка, чтобы знать какой это список по номеру, 1, 2 или 3. Тогда, даже если вы свяжете циклически все списки в один, вы будете знать, какой элемент пришел из какого списка. truct list { int x; int list_id; list* next; }; Когда списки будут созданы, ни один из них не будет пустым. Указатель на следующий элемент каждого списка будет ссылаться на существующий элемент. Окончание одного списка и начало следующего будет определяться по значению переменной list_id. James. |
05.06.2012, 19:44 | 5 |
Увлеченный
|
it is pointer to a reference S in main. and it work well. I have another problem
Это указатель на ссылку S в основной программе. И она работает нормально. У меня другая проблема. |
05.06.2012, 21:06 | 6 |
Увлеченный
Регистрация: 22.05.2012 Последняя активность: 02.12.2015 21:10
Сообщений: 96
Сказал(а) спасибо: 0
Поблагодарили: 0 раз(а) в 0 сообщениях
|
A pointer to a reference is bad form. I have never seen it in over 16 years of C & C++ programming. It makes no sense! It is redundant. It indicates that you don't really understand the functionality of either a pointer or a reference. Try it with just the pointer.
Pass by reference is C++. It does not exist in C. The main reason it was added to C++ is so a class can have functions that return the object of the class itself. This makes it possible to string a series of overloaded operators together. Because the return value of each of those operations is the object of the class. Example: cout << "The value of i is: " << i; There are two calls to the << operator here. The first one returns the whole object cout so that the second one works. Since a reference is the value at its original memory location, a pointer to a reference is just a pointer. Another thing.... You are mixing C style and C++ style programming in the same source code. Don't use printf(...). Use cout << ... I wish I could read your comments! You can also make use of pointer comparison. if(&a == &b) // then a and b are the same object! It might be useful to compare the values of one, two and three inside of your mixlist class to your list pointers. Then you can find the head of each list. Are you taking a class in C++ or are you learning it on your own? James. |
05.06.2012, 22:40 | 7 | ||
Завсегдатай Фонарёвки
|
Цитата:
If there are few ways to do same thing, why can't I choose myself what to use? Each programmer has own style. And the style includes libraries, classes and functions he use, and even comment style and text formatting in source files. You can show another way, but don't say "Don't use", if there is no technical reason. Цитата:
__________________
e-mail: euro@hobbi.tv jabber: shop@hobbi.tv Сообщение: http://forum.hobbi.tv/sendm... |
||
05.06.2012, 23:15 | 8 |
Увлеченный
Регистрация: 22.05.2012 Последняя активность: 02.12.2015 21:10
Сообщений: 96
Сказал(а) спасибо: 0
Поблагодарили: 0 раз(а) в 0 сообщениях
|
Consistency and style is a good reason to use C++ for all it's worth. If you want to use both printf and cout in the same code, you need to realize you are depending on two completely different language header files. You are linking to two different object libraries. It's not impossible or even wrong. It's a matter of simplicity and clarity. Use one form or the other - not both. If you use cout, use cin. If you use printf, use scanf.
Also, if you use only cout, you can easily search the text for every place you output to the terminal. There is nothing wrong with mixing C and C++ in the same project. Just realize that C is C and C++ is C++! The source code for LaserBoy is a very good example of mixing C and C++ in one big project. All of the bitmap stuff is pretty much in C. The rest of it is in C++. |