更改循环C++中的列表值

Changing the value of a list in a loop C++

本文关键字:列表 C++ 循环      更新时间:2023-10-16

我需要一些关于迭代器和基于范围的列表遍历和更新C++帮助。我在 C++ 11 中有以下代码。下面的代码似乎没有修改现有的列表。

auto LIST1 = std::list<Myobject>;
auto LIST2 = std::list<Myobject>;
//Filled lists with Myobjects
// Now I need to swap some values in LIST1 with values in LIST2 if some condition is satisfied
std::list<MyObject>::iterator iter2 = LIST2.begin();
for (auto &el : LIST1){
if (iter2 == LIST2.end()) {break;}
if (el->getSomeProperty() <= 0){
if (iter2->getSomeProperty() >= minValue){
auto temp = el;
el = *iter2;
*iter2 = temp;
}
++iter2; // The iterator moves forward;
}
}

有人可以帮助我吗? 谢谢! PS:我是StackOverflow的新手,所以温柔一点,我不清楚。

问题必须出在您尚未显示的代码中。您显示的代码工作正常。这是一个完全工作的框架,显示显示的代码有效。

#include <list>
#include <iostream>
using namespace std;
int main()
{
std::list<int> list1;
std::list<int> list2;
list1.push_back(10);
list1.push_back(20);
list1.push_back(30);
list2.push_back(1);
list2.push_back(200);
list2.push_back(3);
std::list<int>::iterator iter2 = list2.begin();
for (auto &el : list1)
{
if (iter2 == list2.end()) {break;}
{
if (el > *iter2)
{
auto temp = el;
el = *iter2;
*iter2 = temp;
}
++iter2; // The iterator moves forward;
}
}
for (auto &el : list1)
std::cout << "l1: " << el << std::endl;
for (auto &el : list2)
std::cout << "l2: " << el << std::endl;
}

@David,再次感谢您。我设法解决了这些问题。功能代码如下所示。显然,我搞砸了。

#include <list>
#include <memory>
#include <iostream>
class MyObject{
int value;
public:
MyObject(int m_value){
value = m_value;
}
int getValue() const {return value;}
};

int main(){
std::list<std::shared_ptr<MyObject>> list1;
std::list<std::shared_ptr<MyObject>> list2;
for (int i = 0; i > -10; i--){
list1.emplace_back(std::make_shared<MyObject>(i));
}
for (int i = 0; i < 10; i++){
list2.emplace_back(std::make_shared<MyObject>(i));
}
int minValue = 5;
std::list<std::shared_ptr<MyObject>>::iterator iter2 = list2.begin();
for (auto &el : list1){
if (iter2 == list2.end()) {break;}
if (el->getValue() <= 0){
if ((*iter2)->getValue() >= minValue){
auto temp = el;
el = *iter2;
*iter2 = temp;
}
++iter2; // The iterator moves forward;
}
}
for (auto &obj : list1){
std::cout << obj->getValue() <<std::endl;
}
};