Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

How best to compare two arrays in C++ with unit tests to verify they match?

Currently, I've got a program which reads and extracts multiple pieces of data from a file, and i would like to ensure those values correctly match the expected values, I'm aware of how this should work in other programming languages such as python with lists and tuples etc, however i am unsure as to the best approach to use unit tests within C++ whilst keeping the code as minimal and efficient as possible. I've currently got multiple arrays all of which i wish to verify that they meet their expected values, so i can test the program with differing input files.

To describe this, in essence, i wish to verify the contents of e.g.

int arrayone [5] = { 11, 12, 13, 14, 15 };

are equal to { 11, 12, 13, 14, 15 }

and to complete the unit test successfully if the values are equal, and to fail if they are not equal or not in the same order. Thus, i am looking for the best method to approach this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use a C++ std::array instead and you'll get the benefit from all the methods it exposes, like operator==:

#include <iostream>
#include <array>

int main() {
    std::array arrayone{ 11, 12, 13, 14, 15 };
    std::array facit{ 11, 12, 13, 14, 15 };

    if(arrayone==facit) {
        std::cout << "true
";
    } else {
        std::cout << "false
";
    }
}

Or for C++11 and C++14:

std::array<int, 5> arrayone{ 11, 12, 13, 14, 15 };
std::array<int, 5> facit{ 11, 12, 13, 14, 15 };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...