简体   繁体   中英

how to traversing through vector using iterator and accessing element value?

I started to use iterators for traversing through a vector. Usually, I would use this to go through a vector:

for( int i=0; i< vector.size(); i++){
    cout<<vector[i];
}

I learned if I want to use iterators I would have to do something like this:

vector<int>::iterator col;
for(col = vector.begin(); col != vector.end(); col++){
    cout << *col;
}

But, if I want to access the value at which the iterator is pointing, how would I do that?

I tried to do this:

 int temp = *col;

but this gives an error

Assigning to 'int' from incompatible type 'std::__1::vector<int, std::__1::allocator<int> >'

I am trying this because I have a 2d vector and I'm trying to find the sum of individual columns.

The code you showed is correct... for a 1D vector . But, you say you are actually using a 2D vector , in which case the outer vector's elements are themselves vectors, and so dereferencing an iterator for the outer vector gives you a reference to an inner vector. That is exactly what the error message is complaining about - you are trying to assign an inner vector to an int , which will obviously not work. You would have to iterate that inner vector separately, same as you would have to do when using indexes instead of iterators, eg:

std::vector<std::vector<int> > rows_vec;
...
/*
for(size_t row_idx = 0; row_idx < rows_vec.size(); ++row_idx){
    std::vector<int> &row_vec = rows_vec[row_idx];
    int sum_cols = 0;
    for(size_t col_iter = 0; col_idx < row_vec.size(); ++col_idx){
        sum_cols += row_vec[col_idx];
    }
    // use sum_cols as needed...
}
*/
std::vector<std::vector<int> >::iterator row_iter;
for(row_iter = rows_vec.begin(); row_iter != rows_vec.end(); ++row_iter){
    std::vector<int> &row_vec = *row_iter; 
    std::vector<int>::iterator col_iter;
    int sum_cols = 0;
    for(col_iter = row_vec.begin(); col_iter != row_vec.end(); ++col_iter){
        sum_cols += *col_iter;
    }
    // use sum_cols as needed...
}

If you are using C++11 or later, this can be greatly simplified using range-based for loops :

std::vector<std::vector<int>> rows_vec;
...
for(auto &row_vec : rows_vec){
    int sum_cols = 0;
    for(int col_val : row_vec){
        sum_cols += col_val;
    }
    // use sum_cols as needed...
}

Which could be simplified more by using the standard std::accumulate() algorithm, eg:

std::vector<std::vector<int>> rows_vec;
...
for(auto &row_vec : rows_vec){
    int sum_cols = std::accumulate(row_vec.begin(), row_vec.end(), 0);
    // use sum_cols as needed...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM