traversing a vector in c++ code example

Example 1: c++ iterate through vectgor

std::vector<int> vec_of_ints(100);
for (int i = 0; i < vec_of_ints.size(); i++){
 	std::cout << vec_of_ints.at(i) << " "; 
}
std::cout << std::endl;

Example 2: sort vector struct c++

struct data{
    string word;
    int number;
};


bool my_cmp(const data& a, const data& b)
{
    // smallest comes first
    return a.number < b.number;
}

std::sort(A.begin(), A.end(), my_cmp);

Example 3: declare vectors c++

vector<int> vec;
//Creates an empty (size 0) vector
 

vector<int> vec(4);
//Creates a vector with 4 elements.

/*Each element is initialised to zero.
If this were a vector of strings, each
string would be empty. */

vector<int> vec(4, 42);

/*Creates a vector with 4 elements.
Each element is initialised to 42. */


vector<int> vec(4, 42);
vector<int> vec2(vec);

/*The second line creates a new vector, copying each element from the
vec into vec2. */

Example 4: sorting vector of structs c++

struct data{
    string word;
    int number;
};


bool my_cmp(const data& a, const data& b)
{
    // smallest comes first
    return a.number() < b.number();
}

std::sort(A.begin(), A.end(), my_cmp);

Tags:

Cpp Example