我是初學者,我想問你一些事情。變量中的用戶?
我們有一個數組,其大小取決於用戶在變量'arraysize'中輸入的值。請看下面的代碼和評論,這是否是一個正確的方式來實現這個說的行爲?
int * myArray = NULL;
int arraySize;
cout << "Enter array size: ";
cin >> arraySize;
myArray = new int[arraySize];
delete [] myArray;
我是初學者,我想問你一些事情。變量中的用戶?
我們有一個數組,其大小取決於用戶在變量'arraysize'中輸入的值。請看下面的代碼和評論,這是否是一個正確的方式來實現這個說的行爲?
int * myArray = NULL;
int arraySize;
cout << "Enter array size: ";
cin >> arraySize;
myArray = new int[arraySize];
delete [] myArray;
使用std::vector
作爲C++最佳實踐。
你能告訴我一個例子,你將如何覆蓋下面的代碼爲「正確的解決方案」。謝謝。 ) –
我可以告訴你。但是從文檔中學習對你更好。我寧願你從教程中學習如何使用vector。 –
我明白是的,我會做的..只是想讓你給我一個例子,如果你有一些時間..最好的問候.. –
較早的答案是社區wiki。既然你問了一個例子,這裏有一個更詳細的答案。
A std::vector
是屬於標準模板庫read in detail的一類。
//since you used "using namespace std;" I'm omitting the "std::"
宣言
vector<int> v; //creates a vector of integers
vector<double> vd; //vector of double values
這是非常相似int a[/*any number*/]
。
插入值
v.push_back(5); //adds 5 to the end of the vector (or array of variable size)
又一個示例代碼。
#include <iostream>
#include <vector>
int main()
{
std::vector<int> myvector;
int myint;
std::cout << "Please enter some integers (enter 0 to end):\n";
do {
std::cin >> myint;
myvector.push_back (myint);
} while (myint);
std::cout << "myvector stores " << int(myvector.size()) << " numbers.\n";
return 0;
}
這個程序讀取值,並保存到myvector
直到0
輸入輸入。
迭代
std::vector<int>::size_type sz = myvector.size(); //even int works here
// assign some values:
for (unsigned int i=0; i<sz; i++) myvector[i]=i;
刪除
v.pop_back(); //removes last element
用std :: vector的。 –
工作代碼的評論屬於codereview.stackexchange.com。 –
СhristianHackl,嘿,你對此有何看法?它屬於那裏.. –