Traversing a List of Vectors

Started by
4 comments, last by Stroppy Katamari 11 years ago

in C++ lets say I have a list of vectors like:


std::list<std::vector<int>> myList;

is their any quick way or what would the best way to traverse through that vector in the list? Meaning is their any good way to get every number in that vector, then move onto the next node in the list and getting all of those ints, so on and so on.

I know how to traverse the list on it's on though I'm unsure how to get all the data in that vector for that current list node.

Thanks for any help!!

Advertisement

Well, normally, wouldn't you just use an iterator in a for loop to loop through the list, and get data from the current node? How are you doing it? Are you unsatisfied with the way you do it?

edit:

Ohhh, do you mean iterating through every int that is in those vectors that are in those lists? You could use another for loop to iterate the vector, like you would if you were to iterate through a 2d array.

Or you could write an iterator class for list<vector>, but that might be overkill unless it's used very often.


    std::list<std::vector<int>> intVecList;
    std::list<std::vector<int>>::iterator listIter = intVecList.begin();
    while (listIter != intVecList.end())
    {
        std::vector<int>::iterator vecIter = listIter->begin();
        while (vecIter != listIter->end())
        {
            *vecIter += 5; // add 5 to the current int
            ++vecIter;
        }
        ++listIter;
    }

This is a good way to do it..


    std::list<std::vector<int>> intVecList;
    std::list<std::vector<int>>::iterator listIter = intVecList.begin();
    while (listIter != intVecList.end())
    {
        std::vector<int>::iterator vecIter = listIter->begin();
        while (vecIter != listIter->end())
        {
            *vecIter += 5; // add 5 to the current int
            ++vecIter;
        }
        ++listIter;
    }

This is a good way to do it..

Thanks! That should work for what I need it for! Not sure why I didn't think of that. Thanks again.

If you're using C++11, you can try this too:


#include <vector>
#include <list>
#include <iostream>

int main()
{
  std::list<std::vector<int>> listVectors{{1,2,3},{4,5,6},{7,8,9}};
  for ( auto& vec : listVectors )
    for ( int& i : vec )
      //process each int i
      std::cout << i << std::endl;
}

Yep, the C++11 version with range-for and auto is much better if your compiler supports those things.

Which compiler (exact version) are you using Chad?

This topic is closed to new replies.

Advertisement