C ++中的readfile函数编译错误

问题描述 投票:-2回答:2

我正在尝试制作一个C ++程序,该程序使用ifstream从文件中读取数据。这是我的程序代码:

#include<iostream>
#include<fstream>
#include<string>
#include "sort.h"

std::vector<int> readfile(std::string &filename)
{
    // Open the file 
    std::ifstream file(filename, std::ios::binary);
    // Get the size of the file - seek to end 
    file.seekg(0, file.end);
    std::streampos size = file.tellg();
    // Seek back to start
    file.seekg(0,file.beg);
    // Number of elements is size / sizeof(int)
    int elements = size / sizeof(int);
    // Create an array of data to raead into
    int *temp = new int[elements];
    // Read in data
    file.read((char*)temp, size);
    // Close the file 
    file.close();
    //Copy data into the vector 
    std::vector<int> data(temp, temp + elements);
    // Delete the data
    delete[] temp;
    // Return the vector
    return data;
}

int main(int argc, char **argv)
{
    // Read in a vector
    std::vector<int> data = readfile(std::string("numbers.dat"));
    // Print the vector size 
    std::cout<<"Numbers read = "<<data.size() <<std::endl;
    // Sort the vector 
    sort(data);
    // Output first 100 numbers
    for(int i = 0; i < 100; i++)
    {
        std::cout<<data[i]<<std::endl;
    }
    return 0;
}

头文件sort.cpp是:

#include "sort.h"
#include<iostream>

void sort(std::vector<int> &data)
{
    // Iterate through each value
    for( int i = 0; i< data.size(); ++i)
    {
        // Loop through values above index i 
        for(int j = 0; j < data.size() - (i + 1);  ++j)
        {
           if(data[j] > data[j+1])
            {
                // Swap values 
                int temp = data[j+1];
                data[j+1] = data[j];
                data[j] = temp;
            }
        }
     if(i % 1000 == 0)
     {
     std::cout<<((float)i / (float)data.size()) * 100.0f << "% sorted" << std::endl;
     }      

  }
}

我得到的错误是:

ifstream.cpp: In function ‘int main(int, char**)’:
ifstream.cpp:34:40: error: cannot bind non-const lvalue reference of type ‘std::__cxx11::string& {aka std::__cxx11::basic_string<char>&}’ to an rvalue of type ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’
  std::vector<int> data = readfile(std::string("numbers.dat"));
                                        ^~~~~~~~~~~~~~~~~~~~~
ifstream.cpp:6:18: note:   initializing argument 1 of ‘std::vector<int> readfile(std::__cxx11::string&)’
 std::vector<int> readfile(std::string &filename)

我想知道为什么这不起作用。是GCC不喜欢什么,或者是我,是没有经验的人,他坚持使用C ++。提前致谢 !

c++ c++11 vector readfile ifstream
2个回答
0
投票

函数参数中缺少关键字const。出现此错误的原因是,C ++不希望用户更改临时变量的值,因为它们可以随时从内存中删除。这样做是为了避免传递临时变量的问题然后导致问题。功能定义可以更改为:

std::vector<int> readfile(const std::string &filename)

1
投票

我相信readfile函数定义中的引用导致了问题。如果从函数声明和定义中删除参数中的引用,则代码编译得非常好。

std::vector<int> readfile(std::string filename)
© www.soinside.com 2019 - 2024. All rights reserved.