• 0

[C++] Array of Linked lists Help


Question

Recommended Posts

  • 0
  saiz66 said:
thanks Genesi!  I saved that, it looks to be very helpful. 

I used this declaration:  std::list<int> listArray[10]; 

Now how do I send this to a function as a reference? b/c I want the original to change from the new function.  Thanks!

void f (std::list&lt;int&gt;* myList)
{
 ? ?myList[0].push_back( /* something */ );
}

Hope that helps.

  • 0
  saiz66 said:
thanks bwx, but why do you use *? I am kind of confused, I thought you used & for reference.

I used a pointer because you can't really pass an array as a reference (since an array is implicitly a pointer). The other way you could do it is by using vector objects, but you said you haven't learned that yet so I'll leave that alone.

Hope that helps.

  • 0
  saiz66 said:
thanks bwx for the reply, are arrays the only thing u cant use as a reference or are there any others?

It's not so much that you can't pass arrays by reference, it's just that you can't pass them without pointers. Not unless you want to do some ugly hacking.

  saiz66 said:
Also how can I print all the elments from the list?

To get the value's stored in an std::list, you have to use iterators.

Here's an example:

#include &lt;iostream&gt;
#include &lt;list&gt;

int main (int argc, char **argv)
{
    std::list&lt;int&gt; intList;
    // insert some random numbers into the list
    intList.push_back(1);
    intList.push_back(5);
    intList.push_back(2);
    intList.push_back(4);

    // declare an iterator to iterate through the list and set it to the first element
    std::list&lt;int&gt;::iterator it = intList.begin();

    while (it != intList.end())
    {
        // Currently, 'it' acts as the index. When you dereference 'it', you get the value
        // contained at that index
        std::cout &lt;&lt; *it &lt;&lt; std::endl;

        // Increment the iterator to the next element
        ++it;
    }
    return 0;
}

I commented it the best I could. However, iterators may be a confusing topic so let me know if you don't understand anything.

  bithub said:
actually...

void function(int (&amp;arr)[5])

Granted, there really isnt any reason to pass an array by reference since it will act the same as passing it by value.

Well the array notation in the argument implicitly implies a pointer. All you're doing is passing the actual pointer as a reference. There are reasons to pass an array as a reference but they are very rare. The only reason I can think of is to modify the address pointed to by the pointer you're passing in to the function. For example if you're writing a function to free a block of memory, then zero out the pointer that was just deleted, you could pass the pointer as a reference and set it to zero from within the function and it will retain it's value when the function returns.

I hope that helps.

  • 0
  saiz66 said:
thnx so much for all the help... i am not sure why there is a need for an iterator.

To know why, you have to have some understanding on how linked lists are actually implemented. A linked list is usually a link of structures (can be classes as well) which contain a data variable and a pointer which points to the next element in the linked list. There are also bi-directional linked lists in which each link in the linked list also contains a pointer to the previous link therefore allowing you to go backwards aswell. Now that we're clear on what a linked list is, it is pretty obvious why it requires an iterator. When you first declare an iterator and assign it to the first element in the linked list, that first element has the pointer to the next element. When you increment it, the std::list class internally gets the address of the next link in the linked list through the first element's structure. It keeps doing the same thing with each link in the list until you reach the end. If std::list implemented a method to extract values from the linked list, it would have to iterate the whole list up to the index you specified everytime you requested a value, which is needless to say, rather inefficient.

I know all this is confusing, but it gets better as you go. The key to succeeding in programming is practice. ;)

I hope that helps.

  • 0

yup.. it makes more sense now... I am used to the linked list that we build ourselves. The one where you have a temporary pointer and stuff to traverse through the list. I didn't feel like building my own and thought to use the List from the library. thanks again, much appreciated!!!

  • 0
  saiz66 said:
Also, how would I make it so that when I am passing the array of linked list it won't be changed inside the fucntion? Adding a const infront?

Correct. Placing const will tell the complier that the values are not to be changed. If any attempt by your compiler trys to change them then you will get a error message.

  • 0

Thanks Genesi! I have a problem. I am trying to pass an array of linked list and I have it set as const such as

const list&lt;int&gt;* outstandingRequest

so that it won't change the array of linked lists. But I get an error in this part of the code:

list&lt;int&gt;::iterator it = outstandingRequests[i].begin();

Is that because, it is changing the code?

The error is:

  Quote
error C2440: 'initializing' : cannot convert from 'class std::list<int,class std::allocator<int> >::const_iterator' to 'class st
  • 0
  saiz66 said:
Thanks Genesi!? I have a problem.? I am trying to pass an array of linked list and I have it set as const such as

const list&lt;int&gt;* outstandingRequest

so that it won't change the array of linked lists.? But I get an error in this part of the code:

list&lt;int&gt;::iterator it = outstandingRequests[i].begin();

Is that because, it is changing the code?

The error is:

Since you're passing it as 'const', the array of lists is unchangeable while the iterator you're requesting is not.

Change

list&lt;int&gt;::iterator it = outstandingRequests[i].begin();

into

list&lt;int&gt;::const_iterator it = outstandingRequests[i].begin();

and it'll work fine.

Hope that helps.

  • 0
  bwx said:
Since you're passing it as 'const', the array of lists is unchangeable while the iterator you're requesting is not.

Change

list&lt;int&gt;::iterator it = outstandingRequests[i].begin();

into

list&lt;int&gt;::const_iterator it = outstandingRequests[i].begin();

and it'll work fine.

Hope that helps.

Thats what I meant to say. :p

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Amazon Deal: This Vifa Stockholm 2.0 is one of the best sounding bluetooth speakers by Sayan Sen A few days back we covered some great JBL bluetooth speaker deals across several of its popular models. The discounts are still live and you can check them out in this dedicated piece. Meanwhile for those who prefer more powerful home cinema sound systems, Nakamichi and Samsung are offering the Dragon and Shockwafe models, and the Q-series models, respectively, at their best ever prices. However, if you are someone who is looking for a bit of both, the portability of a bluetooth speaker and the fidelity of a good sounding hi-fi system then the Vifa Stockholm 2.0 Bluetooth Soundbar is something you should look at as it's currently a nice deal (purchase link under the specs table below). While you are not getting a subwoofer with the Vifa Stockholm as it is a 2.0 system, Vifa promises lows down to 42 Hz at +3dB and that should be pretty good for a device lacking a dedicated bass unit; it does pack passive radiators to help with the bass. The Stockholm 2.0 is praised for its sound quality (SQ) and one of the reasons behind it is becasue it has three-way drivers. The technical specifications of the Vifa Stockholm 2.0 Bluetooth Soundbar are given below: Specification Frequency Response 42 Hz – 20 kHz @ ±3 dB Materials Frame: One-piece die-cast aluminium; Enclosure: ABS reinforced; Grills: Kvadrat textile Connectivity Bluetooth® Qualcomm aptX™ HD audio; Wi-Fi Direct & networked (2.4 GHz); Wired optical or analog (3.5 mm mini-jack); USB-disk; Vifa®HOME, Vifa®LINK, Vifa®PLAY Driver Units Tweeter: 2 × 28 mm soft-dome drivers; Midrange: 2 × 80 mm aluminium-cone drivers; Woofer: 4 × 100 mm flat sandwich-cone drivers (force-balanced, backed by 4 passive radiators) Other Features Apple AirPlay & DLNA streaming; DSP signal processing; 6-channel high-performance power amplifier Get it at the link below: Vifa Stockholm 2.0 Bluetooth Soundbar, Nordic Design Soundbar, Smart APP Multi-Room System (Slate Black): $1156.99 (Sold and Shipped by Amazon US) This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
    • Explzh 9.81 by Razvan Serea Explzh is a free Windows archive manager for creating, extracting and managing archives. The program supports many different types of archives, including zip, 7z, rar, tar, ace, lzh, arj, cab, iso, img, msi, sfx and more. Apart from archive creation and extraction, you will also be able to verify compressed data for errors, initiate repair routines, split data into multiple items, and more. It additionally allows you to password protect your data and attach digital signatures to files. Key features of Explzh: Explorer-like GUI and operability. LHA, ZIP (ZIPX), JAR, CAB, RAR, TAR, TAR.XXX, 7z, ARJ, WIM, CHM, PE, HFS, NSIS Format Installer, ISO, InstallShield, MSI, and several other formats... Support for more archive formats by introducing the integrated archiver DLL. Self-extracting archive creation function that can create high-performance automatic installers. Digital signature addition function to created self-extracting archive. Office 2007 or later document compression / image optimization re-archiving function. Supports compression and decompression of Unicode file names. Supports compression and expansion exceeding 4GB. AES encryption function. You can create a robust secure ZIP encryption archive. Thumbnail function of image file. In-library file search function. . Equipped with archive file conversion function. File split function. The split file has a self-consolidation function, and can concatenate files larger than 4GB. (No need for batch file or connection software) UU (XX) Encode, Base64 decode function. FTP upload function Supports Windows 11 shell integration extended context menu. Explzh 9.81 changelog: Improved to send update notifications to the shell when making changes such as additional compression to existing zip and 7-zip files. This also updates the Explorer view of the open file in real time. (If the drop target feature is enabled, you can easily create an encrypted ZIP by dragging and dropping onto the ZIP icon while holding down the Ctrl key.) When the zip drop target setting is enabled, the "Compressed (zipped) Folder" item will be added to the "New" shell context menu if it does not already exist. Password manager bug fix: Fixed a bug that caused the app to crash when reading password.dat (password data) when changing authentication method. Updated to Visual Studio 2022 v.17.14.9. Download: Explzh 64-bit | Explzh 32-bit | ~6.0 MB (Freeware) Download: Explzh ARM64 | 5.9 MB View: Explzh Home Page | Screenshot | Themes Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Have to get that indoctrination in early I guess
    • The reason why I'm using as much portable software as possible.
  • Recent Achievements

    • One Month Later
      Johnny Mrkvička earned a badge
      One Month Later
    • Week One Done
      Sender88 earned a badge
      Week One Done
    • Dedicated
      Daniel Pinto earned a badge
      Dedicated
    • Explorer
      DougQuaid went up a rank
      Explorer
    • One Month Later
      MIghty Haul earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      604
    2. 2
      Michael Scrip
      200
    3. 3
      ATLien_0
      191
    4. 4
      +FloatingFatMan
      138
    5. 5
      Xenon
      126
  • Tell a friend

    Love Neowin? Tell a friend!