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

Und*_*nce 10 c++ vector

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

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

Nav*_*een 12

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


Edw*_*nge 7

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

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

您始终可以设计一个迭代器适配器,该适配器在取消引用时返回应用于其组件迭代器的取消引用的操作的结果.然后你可以将向量复制到输出流:

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

或者,你可以使用for循环...但这有点无聊.