std::sort() c++不工作,但它很简单,为什么:(1D数组
std::sort() C++ not working but its so simple, why :( 1D array
这应该真的很简单,我发现第一个参数是数组名称,第二个是数组的大小+数组名称。然而,它似乎根本没有排序,事实上它什么也没做,嗯,没有在控制台上写任何东西,我是不是做了什么愚蠢的事情?
int main()
{
readFromFile();
system("pause");
return 0;
}
void readFromFile()
{
string line;
int i = 0;
int j;
ifstream file("ACW2_data.txt");
if(file.is_open())
{
getline(file, line);
while (!file.eof())
{
file >> numbers[i];
i++;
int elements = sizeof(numbers) / sizeof(numbers[0]);
**sort(numbers, numbers + elements);**
}
file.close();
}
else
{
cout << "Cant open the file" << endl;
}
for(j = 0; j < i; j++)
{
cout << numbers[j] << endl;
}
system("pause");
}
你们觉得呢?
while (!file.eof())
{
file >> numbers[i];
i++;
int elements = sizeof(numbers) / sizeof(numbers[0]);
**sort(numbers, numbers + elements);**
}
file.close();
while (file >> numbers[i])
{
++i;
}
sort( numbers, numbers + i );
file.close();
或
std::vector<your_int_type> numbers;
your_int_type tmp;
while (file >> tmp)
{
numbers.push_back(tmp);
}
std::sort( numbers.begin(), numbers.end() );
file.close();
编辑:目前,我假设numbers
是int数组。如果没有,我希望你能想出办法来……
int main() {
std::ifstream file("ACW2_data.txt");
std::vector<int> numbers;
file.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
std::copy(std::istream_iterator<int>(file),
std::istream_iterator<int>(),
std::back_inserter(numbers));
std::sort(numbers.begin(), numbers.end());
std::copy(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "n"));
return 0;
}
首先,numbers
定义在哪里,它的类型是什么?
第二,在while循环的每次迭代中,numbers
中的元素数为i
,因此您不需要计算它。
第三,为什么每次插入新元素时都要对numbers
进行排序?为什么不插入所有的元素,然后排序一次呢?在while循环之后
由于您没有显示如何声明numbers
的重要细节,因此我大胆猜测它是一个指针,而sizeof
的技巧未能计算分配的大小。最好使用基于模板的sizeof,比如:
template <typename T, int N>
int array_size( T (&)[N] ) {
return N;
}
或:
template <typename T, int N>
char (&array_size_impl( T(&)[N] ))[N];
#define ARRAY_SIZE( x ) sizeof( array_size_impl( x ) )
因为如果使用指针,这些将触发编译时错误,而不是像sizeof(x)/sizeof(x[0])
技巧那样默默地失败并产生意想不到的结果。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在c++中用vector填充一个简单的动态数组
- (C++)分析树以计算返回错误值的简单算术表达式
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 我的简单if-else语句是如何无法访问的代码
- 使用简单类型列表实现的指数编译时间.为什么
- C++使用数组作为多维数组,尽管将其初始化为带有指针的 1D
- 如何在BST的这个简单递归实现中消除警告
- 一种在C++中读取TXT配置文件的简单方法
- 关于简单C++函数(is_palindrome)的逻辑的问题
- 显示错误输出的简单数组排序程序
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 退出简单while循环时出现问题
- 为什么简单的算术减法在"if"条件下不起作用?
- C++-字符串是否包含一个带有简单循环的单词
- 关于 c++ 函数中指针赋值的简单问题
- 从函数返回任意简单类型的数据
- 如何在没有函数的情况下编写此代码并使C++更简单?
- 有没有办法简单地从 GPU 调用多个 cpp 输出文件?
- std::sort() c++不工作,但它很简单,为什么:(1D数组