I have :
string a[] = {"akdhska","asjd","askjdh"};
Is there any way to get the number of elements in this array?
As a resolution of this I am doing the following:
vector<string> a;
a.insert(a.end(),"test1"); // or a.push_back("test1")
a.insert(a.end(),"test");
a.insert(a.end(),"test12");
a.insert(a.end(),"test123");
int len = a.size();
asked Sep 20, 2015 at 9:37
3 Answers 3
A C++11 solution would be
std::size_t length = std::end(a) - std::begin(a);
or
std::size_t length = std::distance(std::begin(a), std::end(a));
answered Sep 20, 2015 at 9:41
You can probably use :
int length = sizeof(a)/sizeof(*a);
answered Sep 20, 2015 at 9:40
-
best for compile-time known tables, 0 CPU use (at place when is born) BUT NOT when table is passed as argumentJacek Cz– Jacek Cz2015年09月20日 09:44:23 +00:00Commented Sep 20, 2015 at 9:44
-
@JacekCz It depends how it is passed. I.e. what the type of the parameter of the function is.juanchopanza– juanchopanza2015年09月20日 09:45:09 +00:00Commented Sep 20, 2015 at 9:45
string a[] = {"akdhska", "asjd", "askjdh"};
int len = sizeof(a) / sizeof(*a); // gives you number of elements
answered Sep 20, 2015 at 9:40
-
best for compile-time known tables, 0 CPU use (at place when is born) BUT NOT when table is passed as argumentJacek Cz– Jacek Cz2015年09月20日 09:44:27 +00:00Commented Sep 20, 2015 at 9:44
lang-cpp
sizeof(a)/sizeof(*a)
as long you're in the same scopea
was defined.std::vector<std::string> a = {"akdhska","asjd","askjdh"};