2011-08-16 35 views
-1

我怎樣才能獲得dValues[]在該行double dValues[] = {what should i input here?}?因爲我使用的數組。目標是獲得模式。如何從一個矢量的值複製到一個數組?

#include <iostream> 
#include <vector> 
#include <numeric> 

using namespace std; 

double GetMode(double daArray[], int iSize) { 
// Allocate an int array of the same size to hold the 
// repetition count 
int* ipRepetition = new int[iSize]; 
for (int i = 0; i < iSize; ++i) { 
    ipRepetition[i] = 0; 
    int j = 0; 
    bool bFound = false; 
    while ((j < i) && (daArray[i] != daArray[j])) { 
     if (daArray[i] != daArray[j]) { 
      ++j; 
     } 
    } 
    ++(ipRepetition[j]); 
} 
int iMaxRepeat = 0; 
for (int i = 1; i < iSize; ++i) { 
    if (ipRepetition[i] > ipRepetition[iMaxRepeat]) { 
     iMaxRepeat = i; 
    } 
} 
delete [] ipRepetition; 
return daArray[iMaxRepeat]; 
} 


int main() 
{ 
int count, minusElements; 
float newcount, twocount; 
cout << "Enter Elements:"; 
std::cin >> count; 
std::vector<float> number(count); 




cout << "Enter " << count << " number:\n"; 
for(int i=0; i< count ;i++) 
{ 
    std::cin >> number[i]; 
} 

double dValues[] = {}; 
int iArraySize = count; 

std::cout << "Mode = " 
      << GetMode(dValues, iArraySize) << std::endl; 
+0

你的問題,請詳細說明。 – erisco

+0

上一行:雙dValues [] = {};在括號中,我應該輸入什麼來獲取我輸入的變量? – John

回答

0

如果我正確地理解了你,你希望將矢量中的元素複製到數組中。如果是的話 -

float *dValues = new float[count] ; // Need to delete[] when done 
std::copy(number.begin(), number.end(), dValues); 

std::copy是算法頭。但是,爲什麼你想爲這個任務使用/創建原始數組。你已經擁有的矢量number,只是把它傳遞給GetMode(..)

+0

因爲我真的不明白abot std:等等..我只是想研究有關使用數組獲得平均數,中位數和模式的信息。 – John

2

你已經在你的number矢量的所有值,但如果你想這些值複製到一個名爲dValues新的數組,你必須給它分配在堆上(因爲你不知道在編譯時的大小),從載體複製元素,後來騰出內存:

double *dValues = new double[number.size()]; 

for (size_t i = 0; i < number.size(); i++) 
{ 
    dValues[i] = number[i]; 
} 

// whatever you need to do with dValues 

delete [] dValues; 

你也不會檢查你的範圍內您的矢量在for循環中。一個更安全的應用中會使用的vectorpush_back()方法,而不是通過索引分配值。

+0

謝謝你們所有人..我現在明白了.. – John

+0

如果是這樣,你應該給有用的答案的一些信貸的向上票和/或接受答案的形式。這就是社區如何獎勵那些花時間給出高質量答案的人。 –

相關問題