达到列表变量的值
Reaching for the values of variables of a list
我需要在链表中添加变量的值。我可以达到某个值,但不能将 2 个值添加到总和中。
假设我有两个科目,第一个有20分,第二个有10分。
struct subject {
int points;
subject *next;
subject();
};
// testCounter = 2
void list::test(int points, int testCounter) {
subject *test = new subject;
int sum = 0, counter = 0;
for (int i = 1;i <= testCounter;i++,counter++) {
sum += points; // maybe "test->points = points" ??
test = test->next;
}
cout << "nCounter: " << couter; // here I get 2 like I want.
cout << "nSum: " << sum;
}
在"总和"中,我得到 10,第二个值,而不是像我两个值相加后得到的 30。为什么?
是什么: 积分请注意,您永远不会更改它,因此假设您在"test"列表中有 2 个元素所以
void list::test(int points, int testCounter) {
subject *test = new subject;//
^在这里,您创建一个完整的新列表,该列表有 1 个元素,并且它的点值从未初始化过
int sum = 0, counter = 0;
for (int i = 1;i <= testCounter;i++,counter++) {
^处理列表时,请始终检查您是否没有访问空"链"
sum += points; // maybe "test->points = points" ?? <-
更像是总和 += 测试>点;
test = test->next;
}
cout << "nCounter: " << couter; // here I get 2 like I want.
cout << "nSum: " << sum;
}
所以让我们重写它:
a) 假设:
subject *mylist = new subject; // you can make a constructor for an element instead of what i'm going to do
mylist->points = 10;
mylist->next = new subject;
(mylist->next)->points = 20;
(mylist->next)->next = nullptr; //super important remember in c and c++ there's no default value it contain garbage - meaning illegal address
^现在我们基本上将mylist作为两个元素的列表,以最后一个元素结束因此,我们将编写一个函数来获取列表并获取要打印的元素数的 x
void printXElementsInList(const subject *mylist, int x)
{
int counter = 0, sum = 0;
while (mylist && counter < x) /*try to make the same thing without mylist and 3
instead with the same list, without inserting nullptr it will print 2 and 30
cause that's what we have otherwise it will throw an exception!*/
{
sum += mylist->points; //here i'm accessing the points value inside the each chain in the linked list
mylist = mylist->next;
++counter;
}
cout << "counter: " << counter << "nsum: " << sum << endl;
}
请注意,我创建列表的方式非常丑陋,但该功能对您的问题很重要,而不是如何正确创建列表:)HF,希望现在一切都更清楚了
相关文章:
- 函数获取参数的变量列表并将它们转换为一系列字节?
- 分割故障/错误读数变量-C 列表
- 按名称存储和引用变量列表
- 有没有更简单的方法可以做到:if(num1 > num2 && num1 > num3),以获得更大的变量列表进行比较?
- 是否有一种方法可以将变量列表传递给#Define指令,并导致其通过文字值替换字符串值
- 如何在C 中的用户提交变量列表中执行多个操作
- 初始化变量列表中的赋值顺序是否未定义
- C++中将不同类型的变量列表连接到逗号分隔字符串的最快方法是什么?
- 检索C++程序/文件中使用的指针变量列表
- 实例变量列表中的对象未被保留?指针问题
- 简单变量列表参数C++
- C++中的变量列表
- 模板变量"列表"不起作用?
- snprintf变量列表不会将enum转换为char*
- 从C++源文件创建全局变量列表
- 如何在C++中获取类的成员变量列表?
- SpiderMonkey变量列表
- 变量列表中的逗号是序列点吗
- 在可变宏中获取多个变量列表有哪些选项?
- 如何使用文件在SQL或sqsh中输入变量列表