在C++中增加列表的所有元素
Increase all elements of a List in C++
#include <iostream>
#include <vector>
#include <iterator>
#include <iostream>
#include <cmath>
#include <string>
#include <utility>
#include <cstring>
#include <list>
using std::vector;
using std::cout;
using std::list;
using std::endl;
using std::string;
using namespace std;
template <typename T>
void showContents(T& input)
{
typename T::iterator it;
for (it=input.begin(); it != input.end(); it++)
{ cout << *it << " "; }
cout << endl;
}
int main()
{
int B[10] = {0,1,2,3,4,5,6,7,8,9};
cout<< "The first array is: "<< "n";
int i;
for (i = 0; i<10; i++)
{cout<< B[i]<< " ";}
vector<int> KVec(B,B+10);
cout << "n n" << "The first vector is: " << endl;
showContents(KVec);
list<int> BList(B,B+10);
cout << "n" << "The first list is: " << endl;
showContents(BList);
int BCopy [10];
cout<< "n" <<"The second array is: "<< endl;
for(int i = 0; i <10; i++)
{
BCopy[i] = B[i];
BCopy[i] += 2;
cout<< BCopy[i]<< " ";
}
vector<int> KVec2(KVec);
cout<< "n n" << "The second vector is: "<< endl;
for (int i = 0; i<KVec2.size(); i++){
KVec2[i] += 3;
}
showContents(KVec2);
cout<< "n" << "The second list is: "<< endl;
std::list<int> BList2 (BList);
for (std::list<int>::iterator b = BList.begin(); b!=BList.end(); ++b)
{
( *b += 5 );
showContents(BList2);
}
这是我的代码。我能够正确复制所有数组、向量和列表,并相应地增加它们的值。我唯一无法在列表中增加的。我的目标是将第二个列表的所有元素增加 5。我一直在使用多个引用来尝试这样做,但我已经尝试了所有方法,但无法让它工作。下面我有我尝试增加所有值的最新尝试,但这似乎也不起作用,所以现在我需要帮助。这是这项任务中唯一要做的事情,因此任何帮助将不胜感激。谢谢。
由于我的评论解决了您的问题,因此我将其转换为答案。
您使用BList
中的值复制构造BList2
(我正在更改为大括号初始化以避免最烦人的解析)。但是,您再次迭代BList
的值。另外,您不需要*b += 5
两边的括号。最后,您的showContents
函数可能意味着在循环之外。
std::list<int> BList2 {BList};
for (std::list<int>::iterator b = BList2.begin(); b != BList2.end(); ++b)
{
*b += 5;
}
showContents(BList2);
相关文章:
- C++如何通过用户输入删除列表元素
- 访问类lintalizer列表中的结构元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 删除列表中的第n个元素
- 从C++中的对列表中访问特定元素
- 访问动态分配列表中的元素
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 如何在 c++ stl 中获取列表中被推回的元素的地址,在常量时间内?
- 删除列表 c++ 中的最后 3 个元素
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- 有什么方法可以将元素添加到列表中,如图所示?
- 动态分配列表 - 创建一个函数,用于删除所有包含偶数值的元素
- 如何通过保持第一个插入的位置来对列表中插入的其余元素进行排序?
- 如何使用cpp编写选择排序算法以降序对元素列表进行排序?
- (C++)如何创建一个函数来接收两个排序的链表并返回出现在两个列表中的第三个元素列表
- 刷新元素列表视图 QML
- SQLite:通过100K元素列表选择IN
- 解析字符串以创建元素列表
- 向vector添加可变大小元素列表的语法糖
- 是否可以为通用元素列表创建排序