Multiple std::list or std::vector and how to print them out with printf

Hello cpluscplus

First time writing a question on this site, :)

I will try and illustrate my question:

I got two lists or vectors (I think the solution is available to both types)

In one list/vector i got e.g. 5 and the other list e.g. 6

now I want to iterate through both list and print them out accordingly to my illustration

List 1 List2
Value 1 Value 1
Value 2 Value 2
Value 3 Value 3
Value 4 Value 4
Value 5 Value 5
Value 6


My own idea was too use a for-loop with multiple variable in it, but as I understand it doesn't exist in c++ and I haven't figured it out, how to iterate through two lists/vectors that haven't the same size() or length in values in list/vector and get the output like above.


I really hope somebody in this forum can point me to a direction that will learn and educate me.

My Best Regards

David B
You have to use iterator. Just small example(it's valid for both(list and vector)
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 <vector>
#include <iostream>

int main()
{
    typedef std::vector<int> Ints;

    Ints array;
    for(int i = 0; i < 10; ++i)
    {
        array.push_back(i);
    }
    //now array has ten elements from 0 to 9

    Ints::iterator it = array.begin();
    Ints::iterator end = array.end();

    for(; it != end; ++it)
    {
        std::cout << *it << '\n';
    }

    return 0;
}
This is actually pretty tricky because console output is stupid and you have to output line by line.

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
bool printlist[ number_of_lists ] = {false}; // whether or not to print each list
int printcount = 0;  // number of lists to print
std::list<T>::iterator iters[ number_of_lists ]; // iterators

// see how many lists to print
// and prep iterators
for(int i = 0; i < number_of_lists; ++i)
{
  if( !mylist[i].empty() )
  {
    ++printcount;
    printlist[i] = true;
    iters[i] = mylist[i].begin();
  }
}

// print lists
while( printcount > 0 )
{
  for(int i = 0; i < number_of_lists; ++i)
  {
    if(printlist[i])
    {
      cout << *iters[i];
      ++iters[i];
      if(iters[i] == mylist[i].end())
      {
        printlist[i] = false;
        --printcount;
      }
    }
    else // printlist[i] == false
    {
      cout << /*a bunch of spaces */
    }
  }
  cout << endl;
}
Thank you, Disch

Your solution and excellent code was spot on :)

Now it's time to debug your source and see how it works :)

I wish to thank you and keep up your good work :)

Best Regards

David B
Topic archived. No new replies allowed.