Iterating through vectors
Hi,
I am writing code to access vector elements as, to print first "n" elements of vectors out of its total N elements at a time.
For example, Total vector elements : N= 23
Want to print n elements at time : n =3
Can anyone let me know how this can be explored using vectors?
Thanks!
Re: Iterating through vectors
Assuming you mean to print the groups of three on new lines, just iterate over all N elements of the vector, printing a newline character after every three elements have been printed.
Viggy
Re: Iterating through vectors
use a vector<T>::iterator to iterate through the vector
Have a counter that gets incremented each time
if your counter modulus n is zero, then add a newline
Re: Iterating through vectors
If you just want to print first n elements,just iterate from first to 3 using iterator.
regards,
Vatsa
www.objectiveprogramming.com
Re: Iterating through vectors
Quote:
Originally Posted by
ninja9578
use a vector<T>::iterator to iterate through the vector
Have a counter that gets incremented each time
If OP already has the counter anyway, I'd suggest to use that to index the vector. No need for an extra iterator.
Re: Iterating through vectors
Code:
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
int myints[] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 };
std::vector< int > ints( myints , myints + sizeof( myints ) / sizeof( int ) );
size_t offset = 3;
if ( offset < ints.size() )
{
std::for_each( ints.begin() , ints.begin() + offset , []( int v )
{
std::cout << v << std::endl;
} );
}
else
std::cout << "Out of bound" << std::endl;
return 0;
}
Re: Iterating through vectors
Thanks all for your comments.
I implemented it by setting counter limit and incremented this counter value while printing each vector element.