mhmtemnacr
mhmtemnacr

Reputation: 305

Finding the size of certain elements in an array?

how can I find the size of determined members of an array. For example, I declared my array with this:

string myStrArray[200] = {
    "My first string",
    "My second string",
    "My last string"
}

In this code, there are 197 unused elements (or I understand that so). I want to find this array's certain elements (3 elements) by a code such as sizeof(). How can I do that?

Upvotes: 2

Views: 149

Answers (4)

akton
akton

Reputation: 14386

You cannot. However, you can zero the array first then count the number of non-zero elements but this would require the array to contain string* rather than string.

You could use a vector instead, for example:

std::vector<std::string> v;
v.reserve(200); // Allocate space for 200
v.push_back("My first string");
v.push_back("My second string");
v.push_back("My last string");
v.size(); // Returns 3

Upvotes: 4

Benjamin Lindley
Benjamin Lindley

Reputation: 103703

If you know for sure that all of the non-empty strings are at the beginning, then you can use std::find:

int n = std::find(myStrArray, myStrArray + 200, "") - myStrArray;

Actually, you could use std::lower_bound, which is a binary search, and so would be more efficient than std::find. But you'd need a fancy comparison function. One that returns true if the lhs is non-empty and the rhs is empty, false otherwise.

If the non-empty elements are sparsely distributed, you will want to use std::count:

int n = 200 - std::count(myStrArray, myStrArray + 200, "");

Upvotes: 1

mauve
mauve

Reputation: 2016

You cannot use sizeof() to find out how many elements are "filled" in the array, you are storing std::string's in the array (I assume atleast) and all elements will be of the same size (because std::string's do not change size after initialization). No objects change size in C++ actually at least not according to sizeof(); sizeof() will always return the same number for a type because it returns the size of the static type.

If you consider a position in the array to be "filled" when the string does not equal to "", then you can use the following code to count the number of strings:

for (int i = 0; i < 200; ++i)
    if (!myStrArray[i].empty()) ++count;

I would recommend using a std::vector<> instead though (that is almost always a better idea):

std::vector<std::string> my_strings = { "a", "b" }; // requires C++11 in C++03 use push_back()
std::cout << "Number of strings: " << my_strings.size() << std::endl;

Upvotes: 0

uicus
uicus

Reputation: 31

There's no way (at least in C++, what I know) to read out how many elements in array is determined. You have to do it by your own variable (increment it when you "add" elements and decrement when "delete"). You can also use std::vector. vector.size() returns the size of the vector.

Upvotes: 1

Related Questions