2015-10-05 63 views
2

我想在我的數據集中查找最小值。錯誤:'結果'未命名類型

#include <iostream> 
#include <fstream> 
#include <vector> 
#include <algorithm> 
#include <iterator> 


int main(){ 
std::vector<double> v; 
std::ifstream inputFile1("263_V01_C02_R099_THx_BL_128H.dat"); 

if (inputFile1) {   
    double value; 
    while (inputFile1 >> value) { 
     v.push_back(value); 
    } 
} 

auto result = std::min_element(std::begin(v), std::end(v)); 

} 

我已經看到以前的回覆,人們指向迭代器不被包括在內。如何解決這個問題?

+0

它與''沒有任何關係。 –

+1

您使用哪種編譯器? – sergej

+0

@GCC現在工作正常,謝謝! –

回答

3

auto是一個C++ 11說明符。你需要一個C++ 11編譯器。

隨着GCC您可以使用-std=c++11使C++ 11的特點:

GCC的exaple:

g++ -std=c++11 main.cpp 

cppreference.com

auto specifier (since C++11) Specifies that the type of the variable that is being declared will be automatically deduced from its initializer.

如果沒有C++ 11編譯器,那麼你需要定義具體的類型。 例如:

std::vector<double>::iterator result = ... 

順便說一句:std::begin()std::end()也C++ 11的功能。

+0

你怎麼知道GCC正在被使用?而且它有足夠的版本來支持'auto'這個標誌? –

+0

@LightnessRacesinOrbit是的,我正在編譯與gcc,現在工作正常! –

+0

@RichardRublev:請在你的問題中包含這些關鍵細節。 –

2

正如sergej已經指出的auto是一個C++ 11說明符/關鍵字。

如果您無法訪問C++ 11編譯器,則仍然可以使用它來使代碼正常工作。

#include <iostream> 
#include <fstream> 
#include <vector> 
#include <algorithm> 
#include <iterator> 


int main() { 
    std::vector<double> v; 
    std::ifstream inputFile1("263_V01_C02_R099_THx_BL_128H.dat"); 

    if (inputFile1) { 
     double value; 
     while (inputFile1 >> value) { 
      v.push_back(value); 
     } 
    } 

    double result = 0; //Or other default value 
    std::vector<double>::iterator minIter = std::min_element(v.begin(), v.end()); 
    if (minIter != v.end()) 
    { 
     result = (*minIter); 
    } 
    std::cout << "Result is " << result << std::endl; 

} 

的額外提示:

在你的代碼auto是一樣的在這種情況下std::vector<double>::iterator。所以你會得到一個迭代器。

在使用之前,您應該始終檢查一個針對.end()的返回值迭代器。

編輯: 使用v.begin()v.end()而不是std::begin(v)和謝爾蓋和NathanOliver指出std::end(v)作爲。

+1

'std :: begin()'和'std :: end()'是C++ 11的函數 – sergej