gpt4 book ai didi

c++ - 如何在循环遍历 vector 时分配变量?

转载 作者:行者123 更新时间:2023-11-27 22:33:27 24 4
gpt4 key购买 nike

我是 C++ 的新手,我想在一个 vector 中分配两个变量,一个在第一个索引处,另一个在(第一个索引 + 1)处。

这是我目前所拥有的:

#include <iostream>
#include <iterator>
#include <vector>

using std::cout, std::endl, std::vector;

int main() {
vector<int> numList{25, 10, 4, 3, 1, 6};
int var1;
int var2;

// Looping through vector
for(auto it = numList.begin(); it != numList.end(); ++it) {
int index = std::distance(numList.begin(), it);
var1 = numList[index];
var2 = numList[index + 1];
}

cout << "var1: " << var1 << " var2: " << var2 << endl;
}

我希望打印出来:var1: 25 var2: 10

实际输出为:var1:6 var2:0

最佳答案

你的代码大部分都很好,你的期望是错误的。

为什么期待var1: 6 var2: 0

此外,我还更改了您的代码中的两处内容。

  1. int var1 = 0, var2 = 0;

习惯于初始化值

  1. for (auto it = numList.begin(); it < numList.end() -1; ++it)

原始条件 ( for(auto it = numList.begin(); it != numList.end(); ++it) ) 将抛出越界错误,因为它最终会尝试访问大于 vector 大小的索引。

它不会抛出越界错误,因为operator[]未选中,但它仍然作为未定义的行为返回。感谢@Ted Lyngmo。

将您的条件修改为上面我建议的代码以避免未定义的行为。如果您打算使用 .at() ,建议使用 try-catch 来防止 Out-Of-Range。

try{
//... codes
}
catch(const std::out_of_range& e){
cout << "Out of Range Thrown" << endl;
}

修改后的代码

int main() {
vector<int> numList{ 25, 10, 4, 3, 1, 6 };
int var1 = 0, var2 = 0;

// Looping through vector

for (auto it = numList.begin(); it < numList.end() -1; ++it) {
int index = std::distance(numList.begin(), it);
var1 = numList.at(index);
var2 = numList.at(index+1);

cout << "var1: " << var1 << " var2: " << var2 << endl;
}

cout << "Final: var1: " << var1 << " var2: " << var2 << endl;
}

我已经在循环中添加了你的 cout 代码,所以你可以看到循环期间发生了什么。

输出是

The Result

关于c++ - 如何在循环遍历 vector 时分配变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58065487/

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