开发者

How can I copy the values from a vector to an array? [closed]

Closed. This que开发者_如何学Cstion needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 9 years ago.

Improve this question

How can I get the dValues[] in the line double dValues[] = {what should i input here?}?Because I'm using an array. The goal is to get the mode.

#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;


You already have all the values in your number vector, but if you wanted to copy those values into a new array called dValues, you have to allocate it on the heap (since you don't know the size at compile-time), copy the elements from the vector, and later free up that memory:

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;

You're also not checking that you're within the bounds of your vector in the for loop. A safer implementation would use the push_back() method on the vector rather than assigning the values by index.


If I understood you correctly, you wish to copy the elements from the vector to array. If yes -

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

std::copy is in algorithms header. But why do you want to use/create raw array for this task. You already have the vector number and just pass it to GetMode(..)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜