Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

for loop - c++ std::vector: sum in a vector position its previous value

I need to accomplish a simple task, which seems to be forbidden in c++ language.

I have a simple std::vector<double> a{1.,2.,3}and I want to do this simple thing:

for(int i=0; i<a.size();i++)
   a[i]=a[i]+0.1; //or a[i]+=0.1;

or, likely, with pointers:

for (auto it = a.cbegin(); it != a.cend(); ++it)
    *it=*it+0.1;

How can I manage to do it without compiling errors? Thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I do not see an error in this for loop

for(int i=0; i<a.size();i++)
   a[i]=a[i]+0.1;

except that the compiler can issue a warning that there is a comparison of a signed integer with an unsigned integer in the condition of the loop.

You could write the loop like

for( std::vectpr<double>::size_type i=0; i < a.size(); i++ )
   a[i] = a[i]+0.1;

or just like

for( size_t i=0; i < a.size(); i++ )
   a[i] = a[i]+0.1;

In this for loop

for (auto it = myvector.cbegin(); it != myvector.cend(); ++it)
    *it=*it+0.1;

you are using std::vector<double>::const_iterator that may not be used to change elements of the vector.

You could wrute a range-based for loop like

for ( auto &item : myvector ) item += 0.1;

provided that myvector is not a constant object or a reference to a constant object.

Here is a simple demonstrative program.

#include <iostream>
#include <vector>

int main() 
{
    std::vector<double> v = { 1., 2., 3. };
    
    for ( const auto &item : v ) std::cout << item << ' ';
    std::cout << '
';
    
    for ( auto &item : v ) item += 0.1;
    
    for ( const auto &item : v ) std::cout << item << ' ';
    std::cout << '
';
    
    return 0;
}

Its output is

1 2 3 
1.1 2.1 3.1 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...