在C++中增加列表的所有元素

Increase all elements of a List in C++

本文关键字:元素 列表 C++ 增加      更新时间:2023-10-16
#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);