• 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

    • No I don't also get my news for one source. Have you considered that maybe I just don't care about tech enough to spend time reading multiple sources? Anyway my website preferences are way off topic.
    • The bloat on windows after 7 was acceptable, but 11 its even worse than chinese android phone makers, because at least they can remove the ads or apps, but w11 shove you bloat with no option to remove it, it seems that 25h2 will fix that
    • When I say I don't see the appeal, I meant as in general, of the character within the story. I guess apart from being a foil, as mentioned, but I still feel it could probably be done a bit more...less on the nose? A bit more nuanced? Something like that. He really just felt more like a chance to cast Fillion more than anything (to me, anyway). Obviously I am aware that Guy Gardner is not exactly meant to be an *appealing* character
    • This excellent 27-inch 1440p 240Hz QD-OLED gaming monitor is way under $500 by Sayan Sen If you are on the hunt for a great gaming monitor that is under $500, then AOC has a great option today that is worth considering. The model in question is the AOC Q27G4ZD which is a 27-inch 240 Hz display based on QD-OLED (Quantum Dot OLED) and it is at just $428 making it lowest ever priced (purchase link under the specs table below). The specialty of QD-OLED is that pairs the self-emissive OLED pixels with a layer of quantum dots, converting blue OLED light into pure red and green wavelengths more efficiently than traditional color filters. The result is brighter highlights, wider color gamut, and higher color volume without sacrificing OLED’s infinite contrast and instant response. Quantum dots are also said to reduce energy loss in color conversion, while boosting luminance and vibrancy. Thanks to the excellent color reproduction alongside the contrast, this QD-OLED monitor can be used for professional photo/video editing, animations, and such as well, plus working on spreadsheets and other office docs should be a breeze too. The technical specifications of the AOC Q27G4ZD are given below: Specification Details Diagonal Screen Size 26.5 " (67.3 cm) Panel Technology Quantum Dot OLED (QD-OLED) Maximum Refresh Rate 240 Hz (DP 1.4) 144 Hz (HDMI 2.0) Response Time (GtG) 0.03 ms (GtG) Brightness (Typ.) 450 cd/m² (10 % APL) Peak Brightness (HDR) 1000 cd/m² (3 % APL) Color Gamuts RGB 100% (CIE1931) / DCI-P3 99% (CIE1976) Color Accuracy Delta E < 2 Display Colors 1.07Billion HDR Certification VESA DisplayHDR™ True Black 400 Sync Technology Adaptive-Sync Contrast Ratio 1,500,000:1 (Typical) Color Depth 10-bit Connectivity 1 × DisplayPort 1.4 2 × HDMI 2.0 1 × 3.5 mm Audio Out 4x USB 3.2 Gen1 Ergonomics Height: 130 mm Tilt: –5 ° ~ 23 ° Swivel: –30 ° ~ 30 ° Pivot: –90 ° ~ 90 ° Bezel 3-sided frameless Special Features Flicker-Free, Low Blue Mode, Gaming Modes (FPS/Racing/RTS/Gamer1–3), Shadow Control, Game Color, Dial Point, Sniper Scope, Low Input Lag Get the AOC Q27G4ZD 27" QD-OLED at the link below: AOC Q27G4ZD 27" QD OLED Gaming Monitor, 3-Year Zero-Bright-Dot: $427.69 (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.
    • But even when it says local, it is not local, they all send info back. I bet if you unplug your computer from the net, they would not work Not saying that AI can't do useful stuff, just I don't want it pushed onto me all the flipping time
  • Recent Achievements

    • Week One Done
      MIghty Haul earned a badge
      Week One Done
    • One Month Later
      MIghty Haul earned a badge
      One Month Later
    • Collaborator
      KD2004 earned a badge
      Collaborator
    • One Month Later
      ataho31016 earned a badge
      One Month Later
    • One Month Later
      Delahenty Machinery earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      594
    2. 2
      Michael Scrip
      200
    3. 3
      ATLien_0
      192
    4. 4
      +FloatingFatMan
      140
    5. 5
      Xenon
      127
  • Tell a friend

    Love Neowin? Tell a friend!