File: enumerate_view.cpp

package info (click to toggle)
boost1.90 1.90.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 593,156 kB
  • sloc: cpp: 4,190,642; xml: 196,648; python: 34,618; ansic: 23,145; asm: 5,468; sh: 3,776; makefile: 1,161; perl: 1,020; sql: 728; ruby: 676; yacc: 478; java: 77; lisp: 24; csh: 6
file content (74 lines) | stat: -rw-r--r-- 2,164 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Boost.Geometry
// Unit Test

// Copyright (c) 2024 Barend Gehrels, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <string>
#include <vector>

#include <boost/geometry/views/enumerate_view.hpp>
#include <boost/test/included/test_exec_monitor.hpp>

void test_const()
{
    const std::vector<std::string> vec{"cat", "mouse", "squirrel"};
    std::size_t test_index = 0;
    for (auto const& item : boost::geometry::util::enumerate(vec))
    {
        BOOST_CHECK_EQUAL(item.index, test_index++);
        switch(item.index)
        {
            case 0 : BOOST_CHECK_EQUAL(item.value, "cat"); break;
            case 1 : BOOST_CHECK_EQUAL(item.value, "mouse"); break;
            case 2 : BOOST_CHECK_EQUAL(item.value, "squirrel"); break;
        }
    }
}

void test_non_const()
{
    std::vector<std::string> vec{"Amsterdam", "London", "Paris"};
    std::size_t index_sum = 0;
    for (auto const& item : boost::geometry::util::enumerate(vec))
    {
        item.value += " is a city";
        index_sum += item.index;
    }
    BOOST_CHECK_EQUAL(vec[0], "Amsterdam is a city");
    BOOST_CHECK_EQUAL(vec[1], "London is a city");
    BOOST_CHECK_EQUAL(vec[2], "Paris is a city");
    BOOST_CHECK_EQUAL(index_sum, 3);
}

// Verifies the usage of the enumerate_view with C++17 structured bindings
// See https://en.cppreference.com/w/cpp/ranges/enumerate_view
void test_cpp17()
{
#if __cplusplus >= 201703L
    std::vector<int> numbers{1, 3, 5, 7};
    std::size_t sum_indexes = 0;
    int sum_numbers = 0;
    for (auto const [index, num] : boost::geometry::util::enumerate(numbers))
    {   
        sum_indexes += index;
        sum_numbers += num;
        // num is mutable even with const, which does not propagate to reference
        num++;
    }
    BOOST_CHECK_EQUAL(sum_indexes, 6);
    BOOST_CHECK_EQUAL(sum_numbers, 16);
    BOOST_CHECK_EQUAL(numbers[0], 2);
#endif
}

int test_main(int, char* [])
{
    test_const();
    test_non_const();
    test_cpp17();
    return 0;
}