Finding an element in a container

To find an element in a C++ container, or indeed between any pair of InputIterators, use find or find_if.

Use find to find an element with a value you specify. It will return an iterator pointing to the element being sought if successful, and the end of the range if it isn’t found.


#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
std::vector<unsigned int>numbers(3);
std::iota(numbers.begin(), numbers.end(), 4); // Populate with 4, 5, 6
if (std::find(numbers.begin(), numbers.end(), 5) != numbers.end()) {
std::cout << "Found 5" << "\n";
}
else {
}
}


Use find_if to find an element that satisfies a predicate.

#include <vector>
#include <algorithm>
#include <iostream>

struct divides_by_3
{
public:
bool operator()(int i)
{
return i % 3 == 0;
}
};

int main()
{
std::vector<unsigned int>numbers(3);
std::iota(numbers.begin(), numbers.end(), 4); // Populate with 4, 5, 6
std::vector<unsigned int>::const_iterator it =
std::find_if(numbers.begin(), numbers.end(), divides_by_3());
if (it != numbers.end()) {
std::cout << "Found a number that divides by 3: " << *it << "\n";
}
else {
}
}


How to concatenate two vectors in C++

Methods

1. Use std::vector::insert()
2. Use std::copy with a std::back_inserter()
3. Use std::reserve() and then std::copy()
4. Use std::transform() with std::back_inserter()
5. Use std::reserve() and then std::transform()

Method 1: Use std::vector::insert()

    vector1.insert(vector1.end(), vector2.begin(), vector2.end());


Method 2: Use std::copy with a std::back_inserter()

    std::copy(vector2.begin(), vector2.end(), std::back_inserter(vector1));


Method 3: Use std::reserve() and then std::copy()

This means that the vector won’t need to be reallocated during the copy, so may be faster.

    vector1.reserve(vector1.size() + vector2.size());
std::copy(vector2.begin(), vector2.end(), vector1.end());


Method 4: Use std::transform() with std::back_inserter()

This means you can use a functor on the elements of vector2 to modify them or change their type before adding them.

    std::transform(vector2.begin(), vector2.end(), vector1.begin(), transformer());


Method 5: Use std::reserve() and then std::transform()

    vector1.reserve(vector1.size() + vector2.size());
std::transform(vector2.begin(), vector2.end(), vector1.begin(), transformer());


In all cases you can use the new C++11 std::begin() and std::end() functions to get the beginnings and endings of the vectors.