-2

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
6
  • 1
    You can use sizeof(a)/sizeof(*a) as long you're in the same scope a was defined. Commented Sep 20, 2015 at 9:40
  • @πάνταῥεῖ Scope doesn't matter! Commented Sep 20, 2015 at 9:41
  • If you have a somewhat modern compiler, you can also do std::vector<std::string> a = {"akdhska","asjd","askjdh"}; Commented Sep 20, 2015 at 9:45
  • how does sizeof work for the String type? By default do we have a fixed siz for each string? Commented Sep 20, 2015 at 10:45
  • It isn't the string type that matters here, it is the length of the array. Commented Sep 20, 2015 at 11:16

3 Answers 3

6

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
1

You can probably use :

int length = sizeof(a)/sizeof(*a);
answered Sep 20, 2015 at 9:40
2
  • best for compile-time known tables, 0 CPU use (at place when is born) BUT NOT when table is passed as argument Commented 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. Commented Sep 20, 2015 at 9:45
1
string a[] = {"akdhska", "asjd", "askjdh"};
int len = sizeof(a) / sizeof(*a); // gives you number of elements
answered Sep 20, 2015 at 9:40
1
  • best for compile-time known tables, 0 CPU use (at place when is born) BUT NOT when table is passed as argument Commented Sep 20, 2015 at 9:44

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.