gpt4 book ai didi

C++ Persistent Vector,用文本文件中的数据填充 vector

转载 作者:行者123 更新时间:2023-11-28 02:24:45 25 4
gpt4 key购买 nike

我目前正在尝试学习一些 C++,但现在我陷入了一个 vector 练习中。所以任务是从文本文件中读取整数并将它们存储在应该是动态的 vector 中。

我猜 while 循环有什么问题?如果我启动它,程序会失败,如果我将 vector 大小设置为 6,我会得到6 0 0 0 0 0 作为输出。

感谢任何提示。

int main()
{
const string filename = "test.txt";
int s = 0;
fstream f;
f.open(filename, ios::in);
vector<int> v;

if (f){
while(f >> s){
int i = 0;
v[i] = s;
i = i+1;
}

f.close();
}

for(int i = 0; i < 6; i++){
cout << v[i] << "\n";
}

最佳答案

  1. 你不会增长 vector 。它是空的,不能容纳任何 int秒。每次要添加另一个 int 时都需要调整它的大小或者你使用 push_back自动放大 vector 。

  2. 你设置了i = 0对于每次迭代,您将在每次迭代而不是下一次迭代中更改 vector 的第一个值。

去:

    v.push_back(s);

在你的循环中

for(int i = 0; i < v.size(); i++) { // ...

Remark:

You normally don't hardcode vector sizes/bounds. One major point about using std::vector is its ability to behave dynamically with respect to its size. Thus, the code dealing with vectors should not impose any restrictions about the size of the vector onto the respective object.

Example:

for(int i = 0; i < 6; i++){ cout << v[i] << "\n"; }

requires the vector to have at least 6 elements, otherwise (less than 6 ints) you access values out of bounds (and you potentially miss elements if v contains more than 6 values).

Use either

for(int i = 0; i < v.size(); i++){ cout << v[i] << "\n"; }

or

for(std::vector<int>::const_iterator i = v.begin(); i != v.end(); ++i)
{
cout << *i << "\n";
}

or

for(auto i = v.begin(); i != v.end(); ++i)
{
cout << *i << "\n";
}

or

for(int x : v){ cout << x << "\n"; }

or

for(auto && x : v){ cout << x << "\n"; }

or

std::for_each(v.begin(), v.end(), [](int x){ std::cout << x << "\n"; });

or variants of the above which possibly pre-store v.size() or v.end()

or whatever you like as long as you don't impose any restriction on the dynamic size of your vector.

关于C++ Persistent Vector,用文本文件中的数据填充 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31136380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com