How to find the number of elements in an array of strings in C ++?

I have an array of strings.

std :: string str [10] = {"one", "two"}

How to find out how many lines are in the str[] array? Is there a standard feature?

+4
source share
7 answers

If you want to read all sizeof elements, then the technique will work as others have pointed out. If you want to count all non-empty lines, this is one of the possible ways using the standard function count_if .

 bool IsNotEmpty( const std::string& str ) { return !str.empty(); } int main () { std::string str[10] = {"one","two"}; int result = std::count_if(str, &str[10], IsNotEmpty); cout << result << endl; // it will print "2" return 0; } 
+6
source

There are ten lines, even though you only initialized two of them:

 #include <iostream> int main (void) { std::string str[10] = {"one","two"}; std::cout << sizeof(str)/sizeof(*str) << std::endl; std::cout << str[0] << std::endl; std::cout << str[1] << std::endl; std::cout << str[2] << std::endl; std::cout << "===" << std::endl; return 0; } 

Output:

 10 one two === 

If you want to count non-empty lines:

 #include <iostream> int main (void) { std::string str[10] = {"one","two"}; size_t count = 0; for (size_t i = 0; i < sizeof(str)/sizeof(*str); i++) if (str[i] != "") count++; std::cout << count << std::endl; return 0; } 

Outputs 2 as expected.

+6
source

You can always use the countof macro to get the number of elements, but again, memory has been allocated for 10 elements, and this is the count you get.

0
source

Perfect way to do it

 std::string str[] = {"one","two"} int num_of_elements = sizeof( str ) / sizeof( str[ 0 ] ); 
0
source

Since you know the size. You can do a binary search not null / empty.

str [9] is empty
str [5] is empty
str [3] is not empty
str [4] is empty
You have 4 items.

I really don't like to implement the code, but it will be pretty fast.

0
source

Just use this function for an array of 1D strings:

 template<typename String, uint SIZE> // String can be 'string' or 'const string' unsigned int NoOfStrings (String (&arr)[SIZE]) { unsigned int count = 0; while(count < SIZE && arr[count] != "") count ++; return count; } 

Using:

 std::string s1 = {"abc", "def" }; int i = NoOfStrings(s1); // i = 2 

I'm just wondering if we can write a meta program for this! (since everything is known at compile time)

0
source

I do not know that I would use the std :: strings array. If you are already using STL, why not consider a vector or list? At least you could just figure this out with std :: vector :: size () instead of working with ugly magic size. Also, sizeof magic will not work if the array is stored on the heap and not on the stack.

Just do the following:

 std::vector<std::string> strings(10); strings[0] = "one"; strings[1] = "two"; std::cout << "Length = " << strings.size() << std::endl; 
0
source

All Articles