In C++, non-primitive data types are data structures defined by the programmer or provided by the language library. Here are some commonly used non-primitive data types in C++ along with examples:
Non-Primitive Data Types
- Arrays: A collection of elements of the same type, stored in contiguous memory locations.
- Strings: A sequence of characters stored as an array of characters.
- Structures: A composite data type that groups together variables of different data types under a single name.
- Classes: A user-defined data type that encapsulates data and functions within a single unit.
- Pointers: A variable that stores the memory address of another variable.
- Dynamic arrays: An array whose size can be changed at runtime. It is implemented using pointers.
- Map: An associative container that stores elements in the form of key-value pairs.
And Other Data Types such as Linked Lists, Queues, Trees, etc. are Non Primitive Data Types
Example
C++
#include <iostream>
#include <map> // For using map
using namespace std;
int main(){
// Array
int arr[5] = {1, 2, 3, 4, 5};
// String
string name = "John Doe";
// Structure
struct student{
int roll_no;
string name;
float marks;
};
// Class
class rectangle{
int length, width;
public:
int area(){
return length * width;
}
};
// Pointer
int x = 10;
int *ptr = &x;
// Dynamic Array
int *dynamic_arr = new int[5];
// Map
// Use #include<map> for using map
map<string, int> m;
}