|
-
May 2nd, 2012, 10:52 AM
#1
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!
-
May 2nd, 2012, 11:46 AM
#2
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
-
May 2nd, 2012, 12:42 PM
#3
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
-
May 3rd, 2012, 06:26 AM
#4
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
-
May 3rd, 2012, 07:37 PM
#5
Re: Iterating through vectors
 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.
I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.
This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.
-
May 4th, 2012, 10:03 PM
#6
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;
}
-
May 10th, 2012, 12:26 PM
#7
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|