简体   繁体   中英

How to increase every element in a vector by a specified value?

I am trying to create a generic function that will increase every element in a container by a specified value, but I am getting random values outputted to the screen instead. I am assuming it's the memory address that is getting outputted, I am just not sure how to get it to work properly. Any help would be greatly appreciated. Code below.

template<class iterator, class T>
T increment(iterator start, iterator stop, const T & x)
{
    for (iterator itr = start; itr != stop; ++itr)
    {
        itr + x;
    }
}


int main() {

vector<int> v = {1, 2, 3, 4, 5};

cout << increment(v.begin(), v.end(), 5);

return 0;
}

First a function that returns a value other than void and other than main function should return it correctly otherwise if the function fails to provide a valid return value then the result is undefined.

You can change your function increment to look like:

template<typename T>
void increment(std::vector<T>& vec, T val) {
    for (auto& e : vec)
        e += val;
}


int main(){

    std::vector<int> v{ 1, 2, 3, 4, 5 };
    for (const auto& i : v)
        std::cout << i << ", "; 
    std::cout << std::endl; 

    increment(v, 5);

    for (const auto& i : v)
        std::cout << i << ", ";

    std::cout << std::endl;
}

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