这是根据两个变量的内存地址进行数值排序的有效方法吗?
Is this a valid approach for numerical order of two variables by their memory addresses?
我是一个c++新手,我正在阅读Alex Allain写的这本名为《跳入c++》的电子书,这本书非常有帮助。
我最近完成了指针那一章。在本章的最后有一个练习问题,它要求你编写一个程序,比较堆栈中两个不同变量的内存地址,并根据它们的地址的数字顺序打印出变量的顺序。
到目前为止,我让程序运行,但我不满意,如果我实现它的正确方式,我需要一个专家的意见,我的解决方案,以确定我是否朝着正确的方向前进。下面是我自己对这个问题的解决方案(评论和技巧会有所帮助):
// pointersEx05.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
int x,y; // two integer type variables
int *firstVal, *secondVal; // two pointers will point out to an int type variable
std::cout << "enter first value: ";
std::cin >> x; // prompt user for the first value
std::cout << std::endl << "enter second value: ";
std::cin >> y; // prompt user for the second value
std::cout << std::endl;
firstVal = &x; // point to the memory address of x
secondVal = &y; // point to the memory address of y
std::cout << firstVal << " = " << *firstVal; // print out the memory address of the first value and also the value in that address by dereferencing it
std::cout << "n" << secondVal << " = " << *secondVal; // print out the memory address of the second value and also the value in that address by dereferencing it
std::cout << std::endl;
if(firstVal > secondVal){ // check if the memory address of the first value is greater than the memory address of the second value
std::cout << *secondVal << ", "; // if true print out second value first then the first value
std::cout << *firstVal;
}else if(secondVal > firstVal){ // check if the memory address of the second value is greater than the memory address of the first value
std::cout << *firstVal << ", "; // if true print out first value first then the second value
std::cout << *secondVal << ", ";
}
return 0;
}
这是"正确的",但它不是定义良好的行为。只能比较同一数组中元素的地址,或者结构体的同一实例的成员的地址。来自C99 (6.5.8):*
比较两个指针时,结果取决于相对指针所指向对象的地址空间中的位置。如果两个指向对象类型或不完整类型的指针都指向同一个对象,或者都指向同一个数组对象的最后一个元素的后面比较平等的。如果所指向的对象是同一对象的成员聚合对象,指向结构成员的指针稍后声明比较大于指向结构中前面声明的成员的指针,指向下标值较大的数组元素的指针比较大于指向具有lower的同一数组元素的指针下标的价值观。指向同一联合对象成员的所有指针比较平等的。如果表达式P指向数组的一个元素对象,表达式Q指向该对象的最后一个元素数组对象,指针表达式Q+1比较p In
(empahsis矿)
所以这可能是你的导师正在寻找的,它可能会"工作",但就语言标准而言,它仍然是无效的。
* Sectionc++标准的rel]说了类似的东西,但由于类成员的警告等等,它更冗长。它还指出,任何其他内容都是"未指定的",而不是"未定义的"。
作为学术任务这完全没问题。你满足了书中的"要求"
正如其他人所指出的,不指向同一聚合对象的指针的比较是未定义的行为。但是您可以使用std::less来对指针类型进行总排序(参见:http://en.cppreference.com/w/cpp/utility/functional/less)
- 查看数字是否包含在未排序的双数字间隔内的最有效方法?
- 如何使用C++有效地合并排序与向量
- 随机化超大文件内容排序的有效方法是什么?
- 相对于另一个向量对一个向量进行排序 - 最有效的方法
- 何时有效使用存储桶排序以及需要多少存储桶
- 如何有效地对__m256i向量的字节进行重新排序(将int32_t转换为uint8_t)?
- 在排序字符串向量中进行有效搜索
- 当有多个查询时,检查某些子数组是否排序的有效方法是什么?
- C++基数排序的有效方法
- 有效地添加到排序的队列中
- 气泡排序不完全有效
- 合并排序程序总是有效的,但有时会在最后说中止陷阱
- 仅使用几乎相等的标准(无排序)从容器中删除重复项的最有效方法是什么
- 对内存中的大向量进行排序的有效方法
- C++中向量的向量中索引的最有效排序
- 插入最有效的数据结构,然后使用不同的条件进行排序
- 一种在c++中对数组进行bin排序的有效方法
- 最高有效位基数排序如何比最低有效位基数分类更有效
- Cuda有效地将数据插入到未排序的填充数组中
- 在c++中为嵌入式系统排序有效和无效的数字数组