English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ vector data() usage and example

C++ Vector (Container)

In C++11In it, vector has added the usage of data(), which returns a pointer to the first element of the array pointed to by the built-in vector.

Syntax

Vector (vector) 'v' and pointer 'p'. The syntax is:

data_type *p = v.data();

Parameters

It does not contain any parameters.

Return value

It returns a pointer to the array.

Example1

Let's look at a simple example.

#include <iostream>  
#include<vector>  
using namespace std;  
int main()  
{  
vector<int> v{10,20,30,40,50};  
int *k=v.data();  
for(int i=0;i<v.size();i++)  
cout<<*k++<<"  ";  
return 0;  
}

Output Result:

10 20 30 40 50

Example2

Let's look at a simple example.

#include <iostream>
#include<vector>
using namespace std;
int main()
{
vector<string> v{"C","C++","Java",".Net"};
string *k=v.data();
for(int i=0;i<v.size();i++)
cout<<*k++<<"  ";
return 0;
}

Output Result:

C C++ Java .Net

In this example, k is a pointer of string type that points to an element of the vector v.

C++ Vector (Container)