• Advertisement
Sign in to follow this  

Looping through a std::vector

This topic is 2260 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello

I know I can use iterators to loop through vectors, but sometimes this work:


std::vector<DataStruct> Data;

for(int i=0;i<(int)Data.size();i++)
{
Data.Stuff = 123;
}


and some times it does not:


std::vector<DataStruct> Data;

for(int i=0;i<(int)Data.size();i++)
{
char * buffer = Data.pData;
free(buffer);
}


Why does the first method work and the second method produce a "Expresson: vector subscript out of range" error.

Should I always use iterators instead?

Share this post


Link to post
Share on other sites
Advertisement
Where's your condition in the for loop?
You're not comparing the size to anything, so it keeps on going until it gets out of range of the vector and then crashes.

Should probably be something like
for(int i=0;i < (int)Data.size();i++)

Share this post


Link to post
Share on other sites
And what's with the cast? The datatype you should use is size_t, not int.

Share this post


Link to post
Share on other sites
sorry that is a typo, I just wrote it from memory, corrected...

Problem and questions remain.

Why does so many examples I look at use iterators when the above code work?

Share this post


Link to post
Share on other sites
Post actual code that generates an actual error and we can tell you what's wrong with it.

Share this post


Link to post
Share on other sites
Hidden

And what's with the cast? The datatype you should use is size_t, not int.


I am afraid the datatype should be std::vector<DataType>::size_type, which is a royal pain.


This is about the only pretty solution I found:

#include <iostream>

#include <vector>

#include <boost/foreach.hpp>


#define foreach BOOST_FOREACH


int main() {

std::vector<int> v;

v.push_back(1);

v.push_back(2);


foreach(int x, v) {

std::cout << x << '\n';

}

}


Share this post


Link to post

And what's with the cast? The datatype you should use is size_t, not int.


Actually, the datatype you should use is std::vector<DataType>::size_type, which is a royal pain.

This is the only pretty solution I have found:
#include <iostream>
#include <vector>
#include <boost/foreach.hpp>

#define foreach BOOST_FOREACH

int main() {
std::vector<int> v;
v.push_back(1);
v.push_back(2);

foreach(int x, v) {
std::cout << x << '\n';
}
}



EDIT: In C++0x you can do this, which is really nice:
#include <iostream>
#include <vector>

int main() {
std::vector<int> v = {1, 2};

for (int x : v) {
std::cout << x << '\n';
}
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement