c ++向向量的所有元素添加一个整数

问题描述 投票:-4回答:5

我有一个带有整数的向量,可以说{1、2、3、4},我如何向每个元素添加一个常数10来将向量修改为{11、12、13、14}。如果我想将每个元素除以一个int并修改向量,则与divids相同。我一直找不到解决方法。

c++ c++11 vector std add
5个回答
2
投票

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

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

代码:

#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);
}

解决方案2:使用标头算法中标准库(STL)提供的std::for_each函数。这也归结为使用迭代器,但是在此解决方案中,您只需要编写一行即可。

代码:

#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);
}

1
投票

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

std::for_each(std::begin(vec), std::end(vec), [](int& x) { x *= 10; });

但是循环更清晰。


1
投票

考虑使用transform

  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
  );

0
投票

或仅使用for循环,例如:

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

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


0
投票

让我们说{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;
}
© www.soinside.com 2019 - 2024. All rights reserved.