2015-09-20 57 views
-5

刪除了問題和編碼,因爲這不是一個問題,因此可以刪減。向量縮放的C++編輯代碼

+3

錯失問的問題? – P0W

+0

寫的任務是我的問題:)! >這就是我想要做的,我不知道該怎麼做! – Joe

回答

0

第一件事:在要點中,一個向量是一個動態數組。其次,如果您沒有編寫完整的僞代碼佈局,您絕對應該這樣做。

第三,關於你的要點......

1.創建一個矢量對象,將舉行整數

創造近this page(例如部分)底部的向量的幾個例子。

2.要求用戶提供整數數量將被存儲在矢量

只是要求用戶用cin一個整數,這將代表您要生成一個整數的數量(這代表了「帽「你的循環)。

for循環

3.使用在年底

選擇矢量隨機數,並存儲如果你以前從未使用過rand(),檢查this page出來。如果你想有不同的隨機整數,你還需要使用srand()。更多關於srand here

要添加到播放列表的末尾,請查看this page

4.調用displayVector;函數打印出矢量的內容

如果您知道數組如何在C++中工作,則可以訪問矢量的位置完全相同。在示例部分的第二個for循環中,This page正好符合您的要求。

下次查找有關vector容器的文檔。 This page有很多關於它們的信息。

0

僅供將來參考。我們已經有了C++ 11和C++ 14 - 如果你正在學習C++,那麼你可以從現代開始。

#include <iostream> 
#include <vector> 
#include <iomanip> 

using namespace std; 

void displayVector(const vector<int>& myVec); 
void fillTheVector(vector<int>& myVec, const int numberOfElements); 

int main() 
{   
    vector<int> myVector; // 1. Create a vector object that will hold integers 

    cout << "How many random numbers you want to add the vector?" << endl; // 2. Ask user for number of integers to be stored in vector 
    int howManyNumbers = 0; 
    cin >> howManyNumbers; // store the user answer 

    fillTheVector(myVector, howManyNumbers); 
    displayVector(myVector); 
} 

void fillTheVector(vector<int>& vec, const int numberOfElements) 
{ 
    for (int i = 0; i != numberOfElements; ++i) // 3. Use for loop to select random number, and store in the vector at the end 
    { 
     // add random number to the end of the vector 
    } 
} 

void displayVector(const vector<int>& vec) 
{ 
    int cnt = 0; 

    for (const auto& element : vec) 
    { 
     cout << setw(3) << element << " "; 

     if ((++cnt % 15) == 0) 
      cout << endl; 
    } 

    cout << endl; 

    // return; // you do not need to return anything from void function 
} 

HINTS:

  1. 產生隨機數: http://en.cppreference.com/w/cpp/numeric/random/rand
  2. 添加元素的向量的末尾: http://en.cppreference.com/w/cpp/container/vector/push_back