[英]How to find the size of array of vectors? or the number of vectors present in the array
在 C++ 中
如果存在一個對象a
是一個數組, vector<int> a[]
如何獲得的大小a
? 或者,至少,能夠遍歷數組?
我希望能夠遍歷這個所謂的 2D 矩陣中的所有元素。 不確定如何為此實現for
循環。
for(int i = 0; i < ???; i++){
}
a.size()
在這里不起作用。
如果循環在聲明數組的同一個范圍內,則可以直接確定數組的大小,例如:
{
...
vector<int> a[SomeSize];
for(size_t i = 0; i < SomeSize; ++i){ // OK!
...
}
for(size_t i = 0; i < sizeof(a) / sizeof(*a); ++i){ // OK!
...
}
for(size_t i = 0; i < std::size(a); ++i){ // OK!
...
}
for(auto iter = std::begin(a); iter != std::end(a); ++iter){ // OK!
...
}
for(auto &elem : a){ // OK!
...
}
...
}
另一方面,如果數組被傳遞給函數,那么只有當數組通過引用傳遞,或者大小作為單獨的參數顯式傳遞時,才有可能確定數組的大小,例如:
void func1(vector<int> a[]) // same as 'vector<int>* a'
{
for(size_t i = 0; i < sizeof(a) / sizeof(*a); ++i){ // NOPE, can't work!
...
}
for(size_t i = 0; i < std::size(a); ++i){ // NOPE, can't work!
...
}
for(auto iter = std::begin(a); iter != std::end(a); ++iter){ // NOPE, can't work!
...
}
for(auto &elem : a){ // NOPE, can't work!
...
}
}
void func2(vector<int> *a, int size)
{
for(size_t i = 0; i < size; ++i){ // OK!
...
}
for(auto iter = a; iter != a + size; ++iter){ // OK!
...
}
for(auto iter = std::begin(a); iter != std::end(a); ++iter){ // NOPE, can't work!
...
}
for(auto &elem : a){ // NOPE, can't work!
...
}
*/
}
template<size_t N>
void func3(vector<int> (&a)[N])
{
for(size_t i = 0; i < N; ++i){ // OK!
...
}
for(size_t i = 0; i < sizeof(a) / sizeof(*a); ++i){ // OK!
...
}
for(size_t i = 0; i < std::size(a); ++i){ // OK!
...
}
for(auto iter = std::begin(a); iter != std::end(a); ++iter){ // OK!
...
}
for(auto iter = a; iter != a + N; ++iter){ // OK!
...
}
for(auto &elem : a){ // OK!
...
}
}
vector<int> a[SomeSize];
func1(a);
func2(a, SomeSize);
func2(a, std:size(a));
func3(a);
要定義整數的二維矩陣,您需要編寫
std::vector< std::vector< int > > v2d;
要遍歷這個你需要
for( auto& v1d : v2d )
for( int i : v1d )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.