c++ - 如何更改 vector 中元素的值?

标签 c++ vector

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

我现在想做的是学习如何再次访问 vector 并从 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;
}

最佳答案

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

关于c++ - 如何更改 vector 中元素的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4807709/

相关文章:

c++ - 使用 libc++ 在 Mac Yosemite 上访问 std::string 成员时出现链接错误

c++ - 对象数组的选择排序

c++ - 在 C++ 函数中使用内联优化有哪些注意事项?

C++ 访问私有(private) vector 值

C++ 右值引用和 move 语义

java - Java 与 C++ 中的一元运算符

c++ - 使用 std::vector::begin 与 begin(vector)

C++如何检查给定输入是否存在于对 vector 中?

c++ - 如何使用给定特定前缀的 vector 打印出 Trie 中的单词

c++ - 如何从重写的运算符<<迭代 vector 数据成员