C++ 如何更改向量中元素的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4807709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:35:14  来源:igfitidea点击:

How can I change the value of the elements in a vector?

c++vector

提问by UndefinedReference

I have this code, which reads in input from a file and stores it in a vector. So far, I've gotten it to give me the sum of the values within the vector and give the mean of the values using the sum.

我有这段代码,它从文件中读取输入并将其存储在一个向量中。到目前为止,我已经得到它给我向量中值的总和,并使用总和给出值的平均值。

What I'd like to do now is learn how to access the vector again and subtract a value from each element of the vector and then print it out again. For example, once the sum and mean are calculated, I'd like to be able to reprint each value in the terminal minus the mean. Any suggestions/examples?

我现在想做的是学习如何再次访问向量并从向量的每个元素中减去一个值,然后再次打印出来。例如,一旦计算出总和和平均值,我希望能够重新打印终端中减去平均值的每个值。有什么建议/例子吗?

#include <iostream>
#include <vector>
#include <fstream>
#include <cmath>

using namespace std;

int main()
{
    fstream input;
    input.open("input.txt");
    double d;
    vector<double> v;
    cout << "The values in the file input.txt are: " << endl;
    while (input >> d)
    {
        cout << d << endl;
        v.push_back(d);
    }

double total = 0.0;
double mean = 0.0;
double sub = 0.0;
for (int i = 0; i < v.size(); i++)
{
    total += v[i];
    mean = total / v.size();
    sub = v[i] -= mean;
}
cout << "The sum of the values is: " << total << endl;
cout << "The mean value is: " << mean << endl;
cout << sub << endl;
}

回答by Naveen

You can simply access it like an array i.e. v[i] = v[i] - some_num;

您可以像数组一样简单地访问它,即 v[i] = v[i] - some_num;

回答by Edward Strange

Well, you could always run a transform over the vector:

好吧,你总是可以对向量运行变换:

std::transform(v.begin(), v.end(), v.begin(), [mean](int i) -> int { return i - mean; });

You could always also devise an iterator adapter that returns the result of an operation applied to the dereference of its component iterator when it's dereferenced. Then you could just copy the vector to the output stream:

您还可以设计一个迭代器适配器,当它被取消引用时,它返回应用于取消引用其组件迭代器的操作的结果。然后您可以将向量复制到输出流:

std::copy(adapter(v.begin(), [mean](int i) -> { return i - mean; }), v.end(), std::ostream_iterator<int>(cout, "\n"));

Or, you could use a for loop...but that's kind of boring.

或者,您可以使用 for 循环……但这有点无聊。

回答by Nick Banks

You can access the values in a vector just as you access any other array.

您可以像访问任何其他数组一样访问向量中的值。

for (int i = 0; i < v.size(); i++)
{         
  v[i] -= 1;         
} 

回答by Pablo Santa Cruz

Just use:

只需使用:

for (int i = 0; i < v.size(); i++)
{
    v[i] -= valueToSubstract;
}

Or its equivalent (and more readable?):

或者它的等价物(并且更具可读性?):

for (int i = 0; i < v.size(); i++)
    v[i] = v[i] - valueToSubstract;

回答by Jerry Coffin

You might want to consider using some algorithms instead:

您可能需要考虑使用一些算法:

// read in the data:
std::copy(std::istream_iterator<double>(input), 
          std::istream_iterator<double>(),
          std::back_inserter(v));

sum = std::accumulate(v.begin(), v.end(), 0);
average = sum / v.size();

You can modify the values with std::transform, though until we get lambda expressions (C++0x) it may be more trouble than it's worth:

您可以使用 修改值std::transform,但在我们获得 lambda 表达式 (C++0x) 之前,它可能比它的价值更麻烦:

class difference { 
    double base;
public:
    difference(double b) : base(b) {}
    double operator()(double v) { return v-base; }
};

std::transform(v.begin(), v.end(), v.begin(), difference(average));

回答by John Dibling

Your code works fine. When I ran it I got the output:

你的代码工作正常。当我运行它时,我得到了输出:

The values in the file input.txt are:
1
2
3
4
5
6
7
8
9
10
The sum of the values is: 55
The mean value is: 5.5

But it could still be improved.

但它仍然可以改进。

You are iterating over the vector using indexes. This is not the "STL Way" -- you should be using iterators, to wit:

您正在使用索引迭代向量。这不是“STL 方式”——你应该使用迭代器,即:

typedef vector<double> doubles;
for( doubles::const_iterator it = v.begin(), it_end = v.end(); it != it_end; ++it )
{
    total += *it;
    mean = total / v.size();
}

This is better for a number of reasons discussed hereand elsewhere, but here are two main reasons:

由于此处和其他地方讨论的多种原因,这更好,但这里有两个主要原因:

  1. Every container provides the iteratorconcept. Not every container provides random-access (eg, indexed access).
  2. You can generalize your iteration code.
  1. 每个容器都提供了iterator概念。并非每个容器都提供随机访问(例如,索引访问)。
  2. 您可以概括您的迭代代码。

Point number 2 brings up another way you can improve your code. Another thing about your code that isn't very STL-ish is the use of a hand-written loop. <algorithm>s were designed for this purpose, and the best code is the code you never write. You can use a loop to compute the total and mean of the vector, through the use of an accumulator:

第 2 点提出了另一种改进代码的方法。关于您的代码的另一件不是 STL 风格的事情是使用手写循环。 <algorithm>s 就是为此目的而设计的,最好的代码是您从未编写过的代码。通过使用累加器,您可以使用循环来计算向量的总数和平均值:

#include <numeric>
#include <functional>
struct my_totals : public std::binary_function<my_totals, double, my_totals>
{
    my_totals() : total_(0), count_(0) {};
    my_totals operator+(double v) const
    {
        my_totals ret = *this;
        ret.total_ += v;
        ++ret.count_;
        return ret;
    }
    double mean() const { return total_/count_; }
    double total_;
    unsigned count_;
};

...and then:

...进而:

my_totals ttls = std::accumulate(v.begin(), v.end(), my_totals());
cout << "The sum of the values is: " << ttls.total_ << endl;
cout << "The mean value is: " << ttls.mean() << endl;

EDIT:

编辑:

If you have the benefit of a C++0x-compliant compiler, this can be made even simpler using std::for_each(within #include <algorithm>) and a lambda expression:

如果您受益于符合 C++0x 的编译器,则可以使用std::for_each(within #include <algorithm>) 和lambda 表达式使这变得更加简单:

double total = 0;
for_each( v.begin(), v.end(), [&total](double  v) { total += v; });
cout << "The sum of the values is: " << total << endl;
cout << "The mean value is: " << total/v.size() << endl;

回答by Fred Nurk

int main() {
  using namespace std;

  fstream input ("input.txt");
  if (!input) return 1;

  vector<double> v;
  for (double d; input >> d;) {
    v.push_back(d);
  }
  if (v.empty()) return 1;

  double total = std::accumulate(v.begin(), v.end(), 0.0);
  double mean = total / v.size();

  cout << "The values in the file input.txt are:\n";
  for (vector<double>::const_iterator x = v.begin(); x != v.end(); ++x) {
    cout << *x << '\n';
  }
  cout << "The sum of the values is: " << total << '\n';
  cout << "The mean value is: " << mean << '\n';
  cout << "After subtracting the mean, The values are:\n";
  for (vector<double>::const_iterator x = v.begin(); x != v.end(); ++x) {
    cout << *x - mean << '\n';  // outputs without changing
    *x -= mean;  // changes the values in the vector
  }

  return 0;
}