将int添加到向量的所有元素中

问题描述 投票:2回答:5

我有一个带有整数的矢量,可以说{1, 2, 3, 4}

如何将恒定值10添加到每个元素以将向量修改为{11, 12, 13, 14}

如果我想将每个元素都除以int并修改向量,则还有除法。我一直找不到解决方法。

c++ algorithm c++11 add stdvector
5个回答
5
投票

让我们说{1, 2, 3, 4},我如何给一个常数添加10元素,将向量修改为{11, 12, 13, 14}。和相同的divides如果[...]

如何使用std::valarray

std::valarray是用于表示和操作数组的类价值观。它支持element-wise数学运算和各种下标运算符的形式,切片和间接访问。

如果可以使用它们,那只是操作的一行。 std::valarray

See a live demo online

输出:

#include <iostream>
#include <valarray> // std::valarray

int main()
{
   std::valarray<int> valArray{ 1, 2, 3, 4 };
   valArray += 10;  // add each element with 10
   for (const int ele : valArray) std::cout << ele << " ";
   std::cout << "\n";

   valArray /= 2;   // divide each element by 2
   for (const int ele : valArray) std::cout << ele << " ";
   return 0;
}

4
投票

有很多方法可以实现您的目标,但是我将发布其中两种最常用的方法。

解决方案1:您必须使用迭代器来解决您的基本问题。在下面的代码中,我遍历了矢量元素的所有引用并修改了它们的值。

代码:

11 12 13 14 
5 6 6 7 

解决方案2:使用标头算法中标准库(STL)提供的#include <iostream> #include <vector> using namespace std; int main() { vector<int> vec{1, 2, 3, 4}; for(int& x : vec) // if you want to add 10 to each element x += 10; for(int& x : vec) // if you want to divide each element x /= 2; for (int x : vec) // print results printf("%d\n", x); } 函数。这也归结为使用迭代器,但是在此解决方案中,您只需要编写一行即可。

代码:

std::for_each

3
投票

考虑使用#include <iostream> #include <vector> #include <algorithm> // you need to include this to use std::for_each() ! using namespace std; int main() { vector<int> vec{1, 2, 3, 4}; std::for_each(vec.begin(), vec.end(), [](int &n){ n+=10; }); // add 10 to each element std::for_each(vec.begin(), vec.end(), [](int &n){ n/=3; }); // divide each element by 3 for (int x : vec) // print results printf("%d\n", x); }

transform

2
投票

或仅使用for循环,例如:

  std::vector<int> v = { 1, 2, 3, 4 };
  std::transform(
          v.begin(), v.end(),             // The input source
          v.begin(),                      // The output destination
          [](int x) { return x + 10; }    // The transforming function
  );

但是我承认for_each看起来更好...


2
投票

…,或者,如果您不想自己编写循环:

for (auto& item : vec)
{
    item += 10;
}

但是循环更清晰。

© www.soinside.com 2019 - 2024. All rights reserved.