更改循环C++中的列表值
Changing the value of a list in a loop C++
我需要一些关于迭代器和基于范围的列表遍历和更新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;
}
};
相关文章:
- Pybind11:将元组列表从Python传递到C++
- 从链接列表c++中删除一个项目
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- C++如何通过用户输入删除列表元素
- 读取文件的最后一行并输入到链接列表时出错
- 复制列表初始化的隐式转换的等级是多少
- LNK2038、MSVS2017 MAGMA的原因列表
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 没有为自己的结构调用列表推回方法
- 使用简单类型列表实现的指数编译时间.为什么
- 一对向量构造函数:初始值设定项列表与显式构造
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 通过for循环使用用户输入填充列表
- C++:如何使函数只返回作为列表一部分的字符串
- 概念中的cv限定符需要表达式参数列表
- 下面是我为检测链接列表中的循环而制作的代码
- 建议在运行时将带有类实例的列表从c++导入qml
- 如何维护资源管理器项目视图中当前可见的项目列表
- 在卡萨布兰卡形成编码参数的列表
- 在没有参数列表的情况下使用模板名称"Event"无效,模板问题