Ошибка компиляции с функцией readfile в C ++ - PullRequest
0 голосов
/ 05 марта 2019

Я пытаюсь создать программу на 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 ++.Заранее спасибо!

Ответы [ 2 ]

0 голосов
/ 05 марта 2019

Я полагаю, что ссылка в определении функции readfile вызывает проблему.Если вы удалите ссылку из аргумента как из объявления функции, так и из определения, код скомпилируется на отлично.

std::vector<int> readfile(std::string filename)
0 голосов
/ 05 марта 2019

Ключевое слово const отсутствует в аргументах функции.Причиной этой ошибки является то, что C ++ не хочет, чтобы пользователи изменяли значения временных переменных, поскольку они могут быть удалены из памяти в любое время.Это сделано для того, чтобы избежать передачи временных переменных, а затем вызывать проблемы.Определение функции может быть изменено на:

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