Reputation: 179
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.
Upvotes: 1
Views: 276
Reputation: 310990
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 << '\n';
for ( auto &item : v ) item += 0.1;
for ( const auto &item : v ) std::cout << item << ' ';
std::cout << '\n';
return 0;
}
Its output is
1 2 3
1.1 2.1 3.1
Upvotes: 1
Reputation: 91
You can use foreach algorithm and lambda expression:
std::for_each(a.begin(), a.end(), [](double &d){ d += 0.1; });
Upvotes: 0
Reputation: 1215
You could also do it with a range-based for loop
for(auto & e: a) e += 0.1;
Upvotes: 1
Reputation: 75062
std::vector::cbegin()
returns read-only iterators. Use begin()
and end()
instead of cbegin()
and cend()
. Also don't forget to declare myvector
.
std::vector<double> myvector = a;
for (auto it = myvector.begin(); it != myvector.end(); ++it)
*it=*it+0.1;
Upvotes: 1