Exercise: Algorithms

Copy Into std::vector

  • Source C-array is best passed as const char**

  • Use std::copy (here)

#include <gtest/gtest.h>

#include <algo-exercises.h>                            // <--- implement this

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

TEST(stl_exercises_suite, copy_into_vector)
{
    const char* src[] = {"Joerg", "Caro", "Isi", "Johanna"};
    vector<string> dst;

    copy_into_vector(src, 4, dst);                     // <--- implement this

    ASSERT_EQ(dst.size(), 4);
    const vector<string> required_content = {"Joerg", "Caro", "Isi", "Johanna"};
    ASSERT_EQ(dst, required_content);
}

Find Element In std::vector

#include <gtest/gtest.h>

#include <algo-exercises.h>                            // <--- implement this

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

TEST(stl_exercises_suite, find_in_vector)
{
    const vector<string> my_vec = {"Joerg", "Caro", "Isi", "Johanna"};
    
    bool found;

    found = find_in_vector(my_vec, "Isi");             // <--- implement this
    ASSERT_TRUE(found);
    
    found = find_in_vector(my_vec, "Wladimir");        // <--- implement this
    ASSERT_FALSE(found);
}

Sort In-Place

#include <gtest/gtest.h>

#include <sort-in-place.h>        // <--- implement this
#include <vector>

using namespace std;

TEST(stl_exercises_suite, sort_in_place)
{
    vector<int> numbers = {42, 3, 42, 5, 6, 7, 5, 3, 666};

    sort_in_place(numbers);

    vector<int> required_output = {3, 3, 5, 5, 6, 7, 42, 42, 666}; 
    ASSERT_EQ(numbers, required_output);
}

Sort Into A Copy

#include <gtest/gtest.h>

#include <sorted.h>        // <--- implement this
#include <vector>

using namespace std;

TEST(stl_exercises_suite, sorted)
{
    const vector<int> input = {42, 3, 42, 5, 6, 7, 5, 3, 666};
    const vector<int> orig_input = input;

    const vector<int> output = sorted(input);

    const vector<int> required_output = {3, 3, 5, 5, 6, 7, 42, 42, 666}; 
    ASSERT_EQ(output, required_output);
}