std::sort() c++不工作,但它很简单,为什么:(1D数组

std::sort() C++ not working but its so simple, why :( 1D array

本文关键字:简单 1D 数组 为什么 工作 sort c++ std      更新时间:2023-10-16

这应该真的很简单,我发现第一个参数是数组名称,第二个是数组的大小+数组名称。然而,它似乎根本没有排序,事实上它什么也没做,嗯,没有在控制台上写任何东西,我是不是做了什么愚蠢的事情?

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])技巧那样默默地失败并产生意想不到的结果。