-2

My question is that I have two arguments vector<int>& ivec and const int& numb. is there a way to eliminate const int& numb? I just want to do add 10 to all elements in the vector. Also I want to eliminate if part, since it's empty. Thanks in advance. Please do it recursively. My goal it to use as few arguments as possible in a recursive function.

#include <iostream>
#include <vector>
using namespace std;
vector<int> addten(vector<int>& ivec, const int& numb) {
  if (numb == 0) {

  } else { 
    ivec[numb - 1] += 10;
    addten(ivec, numb - 1);
  }
    return ivec;
}
4

1 回答 1

5

你的代码感觉很奇怪。执行此操作的 C++y 方法是:

std::vector<int> vec; // your vector
// adds 10 in place
std::transform(vec.begin(), vec.end(), vec.begin(), 
               std::bind(std::plus<int>(), _1, 10));
// adds 10 out-of-place 
std::vector<int> result;
std::transform(vec.begin(), vec.end(), std::back_inserter(result),
               std::bind(std::plus<int>(), _1, 10));

正如您特别要求的那样,我在 C++ 中实现了一个非常糟糕 的功能,它只能在迭代器上而不是在迭代器上运行。foldlvector<T>

#include <vector>
#include <iostream>

// well, here comes C++ origami
template<typename Start, typename F, typename T>
Start foldl(Start s, F f, const std::vector<T>& v) {
  return foldl_impl(s, f, v, 0);
}

template<typename Start, typename F, typename T>
Start foldl_impl(Start s, F f, const std::vector<T>& v, 
                 typename std::vector<T>::size_type t) {
  if(t == v.size()) return s;
  typename std::vector<T>::size_type t2 = t++;
  return foldl_impl(f(s, v[t2]), f, v, t);
}


int main()
{
  std::vector<int> vec = {1, 2, 3, 4, 5, 6, 7};

  std::vector<int> added = 
    foldl(std::vector<int>()
          , [](std::vector<int>& v, int i) { v.push_back(i+10); return v;}
          , vec);
  for(auto x : added) { 
    std::cout << x << std::endl;
  }

  return 0;
}

请考虑这远非良好的 C++ 风格。

于 2012-05-02T20:57:58.810 回答