A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/cpp_standard_library/cpp_vector_empty.htm below:

C++ Vector Empty Method

C++ vector::empty() Function

The C++ vector::empty() function is used to determine whether a given vector is empty or not. If the vector size is 0, it returns true; otherwise, it returns false. It is a library function of the <vector> header. The complexity of the empty() function is constant.

Vectors are almost similar to dynamic arrays, they have the ability to automatically resize themselves when an item is added or removed, with the container handling its storage automatically. The vector elements are stored in contiguous space that can be accessed as well as traversed with the help of iterators.

Syntax

Following is the syntax for C++ vector::empty() Function −

bool empty() const noexcept;
Parameters

It doesn't accept any kind of parameter.

Example 1

Let's consider the following example, where we are going to use empty() function.

#include <iostream>
#include <vector>
using namespace std;

int main(){
   vector<int> tutorial{};
   if (tutorial.empty()){
      cout << "TRUE";
   }else {
      cout << "FALSE";
   }
   return 0;
}
Output

When we compile and run the above program, this will produce the following result −

TRUE
Example 2

Considering the another scenario, where we are going to use push_back() function to insert the elements and check whether the vector is empty or not.

#include <iostream>
#include <vector>
using namespace std;

int main(){
   vector<int> myvector;
   myvector.push_back(11);
   myvector.push_back(22);
   cout << "Total Elements: " << myvector.size() << endl;
   if (myvector.empty())
      cout << "TRUE" << endl;
   else
      cout << "FALSE" << endl;
   return 0;
}
Output

On running the above program, it will produce the following result −

Total Elements: 2
FALSE
Example 3

In the following example, we are going to subtract the elements in the vector.

#include <iostream>
#include <vector>
using namespace std;

int main(){
   int x = 0;
   vector<int> myvector{11,22,33,44,55};
   while (!myvector.empty()){
      x = x - myvector.back();
      myvector.pop_back();
   }
   cout << x;
   return 0;
}
Output

On running the above program, it will produce the following result −

-165

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4