6

In unit test code in C++, when I need to compare two vectors, I create temporary vector to store expected values.

std::vector<int> expected({5,2,3, 15});
EXPECT_TRUE(Util::sameTwoVectors(result, expected));

Can I make it one line? In python, I can generate a list with "[...]".

sameTwoVectors(members, [5,2,3,15])
prosseek
  • 182,215
  • 215
  • 566
  • 871
  • You're looking for a vector literal. Does [this](http://stackoverflow.com/questions/758118/c-vector-literals-or-something-like-them) answer help? – David Robinson Jun 16 '13 at 01:29

2 Answers2

3

Since std::vector includes an initializer-list constructor that takes a std::initializer_list you can use the uniform initialization syntax as long as the sameTwoVectors function accepts a vector by value, rvalue reference or const reference.

namespace Util
{
    bool sameTwoVectors(
        const std::vector<int>& result,
        const std::vector<int>& expected)
        {
            return result == expected;
        }
}


int main()
{
    std::vector<int> result;

    EXPECT_TRUE(Util::sameTwoVectors(result, {5,2,3,15}));
}

Optionally, if sameTwoVectors only does a simple comparison you can eliminate it. Just use a comparison expression in its place when you call EXPECT_TRUE. The trade-off is that you have to specify std::vector<int> explicitly instead of relying on the implicit conversion constructor. It's a couple of characters less and a bit clearer what the expected result is.

EXPECT_TRUE(result == std::vector<int>({5,2,3,15}));
Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
  • It's worth noting that there's a specific term for that. It has an initializer-list constructor. See N3485 § 8.5.4/2. – chris Jun 16 '13 at 02:24
1

If Util::sameTwoVectors expects const reference or just a value you can (assuming C++11 support) write it like that

EXPECT_TRUE(Util::sameTwoVectors(result, std::vector<int>{5, 2, 3, 15}));
JJJ
  • 2,731
  • 1
  • 12
  • 23