Can someone explain to me why the following code for a unit test gives the error unreadVariable for n and k in cppcheck?
Combinations is a template class that calculates all combinations of n choose k but this should not matter here.
TEST(Combinations, ChooseOne)
{
const UINT8 n = 3;
const UINT8 k = 1;
Combinations<n, k> comb;
comb.calc();
std::vector< std::vector<UINT8> > _vui8Expect = { { 2 }, { 1 }, { 0 } };
EXPECT_THAT(comb.result, ::testing::ContainerEq(_vui8Expect));
}
I can change the code to the following and not get a cppcheck error anymore. But I do not like this, because it make the code less verbose. n, k are well defined quantities in statistics and they make it more clear in the call what is going on.
TEST(Combinations, ChooseOne)
{
Combinations<3, 1> comb;
comb.calc();
std::vector< std::vector<UINT8> > _vui8Expect = { { 2 }, { 1 }, { 0 } };
EXPECT_THAT(comb.result, ::testing::ContainerEq(_vui8Expect));
}
This is a known issue: http://trac.cppcheck.net/ticket/7542
So unless it will be fixed, the cppcheck will report this false positive.
I tried to put this in a comment, but here is a thought.
As far as I remember Google Tests is using TEST clause in a following manner:
TEST(test_case_name, test_name) {
... test body ...
}
I haven't personally encountered something similar, but in your case you have the very same name for the test case name, and the actual class you test.
To me it seems like some sort of name collision.
Have you tried renaming
TEST(Combinations, ChooseOne)
{
const UINT8 n = 3;
const UINT8 k = 1;
Combinations<n, k> comb;
comb.calc();
std::vector< std::vector<UINT8> > _vui8Expect = { { 2 }, { 1 }, { 0 } };
EXPECT_THAT(comb.result, ::testing::ContainerEq(_vui8Expect));
}
to a:
TEST(CombinationsTest, ChooseOne)
{
const UINT8 n = 3;
const UINT8 k = 1;
Combinations<n, k> comb;
comb.calc();
std::vector< std::vector<UINT8> > _vui8Expect = { { 2 }, { 1 }, { 0 } };
EXPECT_THAT(comb.result, ::testing::ContainerEq(_vui8Expect));
}
Related
I have 2 lists:
distancestring[1][3], with the following values:
distancestring[0][0]=3.4
distancestring[0][1]=2
distancestring[0][2]=1.1
distancestring[1][0]=5
distancestring[1][1]=4.2
and imagestring[1][3], with the following values:
imagestring[0][0]="ccc"
imagestring[0][1]="aaa"
imagestring[0][2]="ddd"
imagestring[1][0]="bbb"
imagestring[1][1]="eee"
I would like to have a third list "result" with values of imagestring according to distancestring order.
Result should have items:
result[0][0]="ddd"
result[0][1]="aaa"
result[0][2]="ccc"
result[1][0]="eee"
result[1][1]="bbb"
Hope I made my self clear.
I am sure the following can be done more efficient but here is my suggestion on how it can be done.
Please note that it is important that distancestring and imagestring does have the same structure of elements like your example.
void main() {
final distancestring = [
[3.4, 2, 1.1],
[5, 4.2]
];
final imagestring = [
['ccc', 'aaa', 'ddd'],
['bbb', 'eee']
];
print(distancestring); // [[3.4, 2, 1.1], [5, 4.2]]
print(imagestring); // [[ccc, aaa, ddd], [bbb, eee]]
print(sort(
distancestring,
imagestring,
(dynamic d1, dynamic d2) =>
d1.compareTo(d2) as int)); // [[ddd, aaa, ccc], [eee, bbb]]
}
class Pair<A, B> {
final A a;
final B b;
const Pair(this.a, this.b);
}
List<List<B>> sort<A, B>(List<List<A>> distancestring,
List<List<B>> imagestring, int Function(A, A) compare) {
final temp = <Pair<A, B>>[];
for (var i = 0; i < distancestring.length; i++) {
for (var k = 0; k < distancestring[i].length; k++) {
temp.add(Pair(distancestring[i][k], imagestring[i][k]));
}
}
temp.sort((e1, e2) => compare(e1.a, e2.a));
var count = 0;
final result = <List<B>>[];
for (var i = 0; i < distancestring.length; i++) {
final list = <B>[];
for (var k = 0; k < distancestring[i].length; k++) {
list.add(temp[count++].b);
}
result.add(list);
}
return result;
}
class CRA_Account {
int tax[4];
double refund[4];
int SIN;
public:
CRA_Account();
}
CRA_Account::CRA_Account() {
SIN = 0;
tax[4] = { 0 };
refund[4] = { 0 };
}
When I create a object in main it'll set the SIN to 0 but won't do the same to the arrays. Can someone help why?
tax[4] = { 0 }; is wrong at many levels..
One way to initlizie your class:
CRA_Account::CRA_Account():
tax{0,0,0,0},
refund{0,0,0,0},
SIN{0}{
}
Online
Try to have a look at std::array
Templates generally are inline - you have to supply the definition with the declaration.
Global (static) data requires that there be exactly one definition of the data (but it can be declared multiple times).
So, for a class with static data, one normally declares the static in the class definition (header), and the storage as static in the implementation file (.cpp).
But what does one do for a template that needs to refer to static / global data?
Here's a bit of code to give you something somewhat concrete to consider:
// we represent in a formal manner anything that can be encoded in a MSVS format specification
// A format specification, which consists of optional and required fields, has the following form:
// %[flags][width][.precision][{h | l | ll | w | I | I32 | I64}] type
// based on https://msdn.microsoft.com/en-us/library/56e442dc.aspx
struct FormatSpec
{
enum Size {
normal,
h,
l,
ll,
w,
I,
I32,
I64
};
enum Type {
invalid,
character,
signed_integer,
unsigned_integer,
unsigned_octal,
unsigned_hex,
floating_point,
expontential_floating_point,
engineering_floating_point,
hex_double_floating_point,
pointer,
string,
z_string
};
unsigned fLeftAlign : 1;
unsigned fAlwaysSigned : 1;
unsigned fLeadingZeros : 1;
unsigned fBlankPadding : 1;
unsigned fBasePrefix : 1;
unsigned width;
unsigned precision;
Size size_;
Type type_;
};
struct FormatSpecTypeDatum
{
FormatSpec::Type id; // id
const TCHAR * symbol; // text symbol
};
FormatSpecTypeDatum kTypeSpecs[] =
{
{ FormatSpec::character, _T("c") },
{ FormatSpec::character, _T("C") },
{ FormatSpec::signed_integer, _T("d") },
{ FormatSpec::signed_integer, _T("i") },
{ FormatSpec::unsigned_octal, _T("o") },
{ FormatSpec::unsigned_integer, _T("u") },
{ FormatSpec::unsigned_hex, _T("x") },
{ FormatSpec::unsigned_hex, _T("X") },
{ FormatSpec::expontential_floating_point, _T("e") },
{ FormatSpec::expontential_floating_point, _T("E") },
{ FormatSpec::floating_point, _T("f") },
{ FormatSpec::floating_point, _T("F") },
{ FormatSpec::engineering_floating_point, _T("g") },
{ FormatSpec::engineering_floating_point, _T("G") },
{ FormatSpec::hex_double_floating_point, _T("a") },
{ FormatSpec::hex_double_floating_point, _T("A") },
{ FormatSpec::pointer, _T("p") },
{ FormatSpec::string, _T("s") },
{ FormatSpec::string, _T("S") },
{ FormatSpec::z_string, _T("Z") },
};
template <typename ctype>
bool DecodeFormatSpecType(const ctype * & format, FormatSpec & spec)
{
for (unsigned i = 0; i < countof(kTypeSpecs); ++i)
if (format[0] == kTypeSpecs[i].symbol[0])
{
spec.type_ = kTypeSpecs[i].id;
++format;
return true;
}
return false;
}
It's relatively simple - a symbolic ID to character representation lookup table.
I want to be able to use DecodeFormatSpecType<>() for char, unsigned char, wchar_t, etc.
I could remove the template from DecodeFormatSpecType() and just supply overloaded interfaces for various character types.
The main thing is that the data isn't really changing - an unsigned char 'c' and a wchar_t 'c' and a legacy char 'c' have the exact same value, regardless of the character's storage size (for core ASCII characters this is true, although there are undoubtedly some other encodings such as EDBIC where this isn't true, that's not the problem I'm attempting to solve here).
I just want to understand "how do I construct my C++ libraries so that I can access global data defined in exactly one location - which is stored as an array - and I want the accessing templated code to know the length of the global data, just like I can with normal non-templated code have a global symbol table like what I've shown in my example code by having the table and the implementation that needs its size both exist in the appropriate .cpp file"
Does that make sense?
global data + functions that need to know the exact definition but also can be presented (with an interface) this generic (to a valid domain).
A function template can use global functions and global data without any problem.
If you want to encapsulate the definition of kTypeSpecs and not have it defined in a header file, you can use couple of functions to provide access to the data.
size_t getNumberOfTypeSpecs();
// Provide read only access to the data.
FormatSpecTypeDatum const* getTypeSpecs();
and then implement DecodeFormatSpecType as
template <typename ctype>
bool DecodeFormatSpecType(const ctype * & format, FormatSpec & spec)
{
size_t num = getNumberOfTypeSpecs();
FormatSpecTypeDatum const* typeSpecs = getTypeSpecs();
for (unsigned i = 0; i < num; ++i)
if (format[0] == typeSpecs[i].symbol[0])
{
spec.type_ = typeSpecs[i].id;
++format;
return true;
}
return false;
}
The functions getNumberOfTypeSpecs and getTypeSpecs can be implemented in a .cpp file as:
// Make the data file scoped global variable.
static FormatSpecTypeDatum kTypeSpecs[] =
{
{ FormatSpec::character, _T("c") },
{ FormatSpec::character, _T("C") },
{ FormatSpec::signed_integer, _T("d") },
{ FormatSpec::signed_integer, _T("i") },
{ FormatSpec::unsigned_octal, _T("o") },
{ FormatSpec::unsigned_integer, _T("u") },
{ FormatSpec::unsigned_hex, _T("x") },
{ FormatSpec::unsigned_hex, _T("X") },
{ FormatSpec::expontential_floating_point, _T("e") },
{ FormatSpec::expontential_floating_point, _T("E") },
{ FormatSpec::floating_point, _T("f") },
{ FormatSpec::floating_point, _T("F") },
{ FormatSpec::engineering_floating_point, _T("g") },
{ FormatSpec::engineering_floating_point, _T("G") },
{ FormatSpec::hex_double_floating_point, _T("a") },
{ FormatSpec::hex_double_floating_point, _T("A") },
{ FormatSpec::pointer, _T("p") },
{ FormatSpec::string, _T("s") },
{ FormatSpec::string, _T("S") },
{ FormatSpec::z_string, _T("Z") },
};
size_t getNumberOfTypeSpecs()
{
return sizeof(kTypeSpecs)/sizeof(kTypeSpecs[0]);
}
FormatSpecTypeDatum const* getTypeSpecs()
{
return kTypeSpecs;
}
Update, in response to comment by OP
Yes, you can. The following are perfectly valid:
size_t getNumberOfTypeSpecs()
{
static constexpr size_t num = sizeof(kTypeSpecs)/sizeof(kTypeSpecs[0]);
return num;
}
constexpr size_t getNumberOfTypeSpecs()
{
return sizeof(kTypeSpecs)/sizeof(kTypeSpecs[0]);
}
I am trying to implement the game Deal or no deal, i have two classes, Box & Player. in box is stored the vector game_box and in Player I want to store the box and the money that the player has to keep till the end of the game.
I have tried to implement it in this way. it runs correctly, without no errors, but when i try to verify if the values were stored into the setter, it just give me that the setter is empty. I really dont understand why! does anybody knows why?
class Box
{
vector<Box> game_box;
float pound_contained;
int box_number;
public:
Box(int box_number, float pound_contained);
Box();
int getbox_number();
float getpound_contained();
};
class Player :public Box
{
int player_box;
float player_money;
public:
Player();
~Player();
float getplayer_money();
int getplayer_box();
void setplayer_money(float);
void setplayer_box(int);
};
void Player::setplayer_money(float)
{
player_money = player_money;
}
void Player::setplayer_box(int)
{
player_box = player_box;
}
float Player::getplayer_money()
{
return this->player_money;
}
int Player::getplayer_box()
{
return this->player_box;
}
int main()
{
vector<Box> game_box;
srand(time(0));
int n;
Player money;
Box oper;
float myArray [22][2] = { { 0.01, 0 }, { 0.10, 0 }, { 0.50, 0 },
{ 1, 0 }, { 5, 0 }, { 10, 0 },
{ 50, 0 }, { 100, 0 }, { 250, 0 },
{ 500, 0 }, { 750, 0 }, { 1000, 0 },
{ 3000, 0 }, { 5000, 0 }, { 10000, 0 },
{ 15000, 0 }, { 20000, 0 }, { 35000, 0 },
{ 50000, 0 }, { 75000, 0 }, { 100000, 0 },
{ 250000, 0 }
};
//random assignation of pound value to the 22 boxes
for (int e = 1; e <22; e++)
{
int pos;
bool op = true;
while (op)
{
pos = rand() % 22 + 1;
if (myArray[pos][1] == 0)
{
myArray[pos][1] = 1;
op = false;
}
}
Box b(e, myArray[pos][0]); //creating the class game
game_box.push_back(b); //function of the vector to insert a data in it
}
// random assignment of a box to the player
int i = rand() % 22 + 1;
Box* boxes = &game_box[i];
cout << "Your box is going to be the box number: "<< boxes->getbox_number()<<endl;
////////////////////////////////////////////////////////////////////setter not working
money.setplayer_money(boxes->getpound_contained());
money.setplayer_box(oper.getbox_number());
cout << money.getplayer_box() << " " << money.getplayer_money() << endl << endl;
game_box.erase(game_box.begin()+i);
return 0;
}
There are not "setters" or "getters" in C++ that are distinct from other method calls. So you write them just as you would any other method.
To elaborate on the problem pointed out by #maniek, you wrote:
void Player::setplayer_money(float)
{
player_money = player_money;
}
C and C++ have the ability to specify method and function arguments without names--just types. This might seem a little strange as there is no way to access that parameter (at least not a way that is guaranteed to work in all compilers or optimization levels, you can possibly do it by messing with the stack). So what you are doing here is just setting the member player_money to itself.
(Note: If you are wondering why it allows you to specify a method argument without a name, it has a few uses...one is that not naming it suppresses warning messages that you aren't using that parameter. So it is a way of marking something as not being used at the current time, yet still required--perhaps for legacy reasons or perhaps because you might use it in the future.)
You can give a new name to the parameter that doesn't overlap with the name of the member variable:
void Player::setplayer_money(float new_player_money)
{
player_money = new_player_money;
}
That's one way of avoiding ambiguity. Because in terms of what value is in scope, the parameter will win over the member variable. So this would be another do-nothing operation, that would assign the parameter value to itself:
void Player::setplayer_money(float player_money)
{
player_money = player_money;
}
(Note: Since player_money is passed by value and not by reference, that wouldn't change the parameter's value at the calling site. In particular, how could it change the value, if you passed in a constant like 10.20.)
What #maniek suggested is that a way to disambiguate in that case is to use this->player_money when you mean the member variable and player_money when you mean the argument to the method. Another thing some people do is name their member variables specially--like start them with m_ as in m_player_money:
void Player::setplayer_money(float player_money)
{
m_player_money = player_money;
}
(Note: You can also just use an underscore prefix with no m as long as the next character is lowercase, but some people consider that too dangerous as underscores followed by capital letters are reserved for compiler internal usages.)
As a final thought--if the class name is Player then it's already implicit whose money you are setting (the player's) so you could just call it set_money. Furthermore, I'm not a fan of underscores in names (more common in C than C++) so I'd probably call it setMoney.
How about:
void Player::setplayer_money(float player_money)
{
this->player_money = player_money;
}
?
I have List List<MyType>, my type contains Age and RandomID
Now I want to find the maximum age from this list.
What is the simplest and most efficient way?
Assuming you have access to LINQ, and Age is an int (you may also try var maxAge - it is more likely to compile):
int maxAge = myTypes.Max(t => t.Age);
If you also need the RandomID (or the whole object), a quick solution is to use MaxBy from MoreLinq
MyType oldest = myTypes.MaxBy(t => t.Age);
Okay, so if you don't have LINQ, you could hard-code it:
public int FindMaxAge(List<MyType> list)
{
if (list.Count == 0)
{
throw new InvalidOperationException("Empty list");
}
int maxAge = int.MinValue;
foreach (MyType type in list)
{
if (type.Age > maxAge)
{
maxAge = type.Age;
}
}
return maxAge;
}
Or you could write a more general version, reusable across lots of list types:
public int FindMaxValue<T>(List<T> list, Converter<T, int> projection)
{
if (list.Count == 0)
{
throw new InvalidOperationException("Empty list");
}
int maxValue = int.MinValue;
foreach (T item in list)
{
int value = projection(item);
if (value > maxValue)
{
maxValue = value;
}
}
return maxValue;
}
You can use this with:
// C# 2
int maxAge = FindMaxValue(list, delegate(MyType x) { return x.Age; });
// C# 3
int maxAge = FindMaxValue(list, x => x.Age);
Or you could use LINQBridge :)
In each case, you can return the if block with a simple call to Math.Max if you want. For example:
foreach (T item in list)
{
maxValue = Math.Max(maxValue, projection(item));
}
int max = myList.Max(r => r.Age);
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.max.aspx
var maxAge = list.Max(x => x.Age);
thelist.Max(e => e.age);
Easiest way is to use System.Linq as previously described
using System.Linq;
public int GetHighestValue(List<MyTypes> list)
{
return list.Count > 0 ? list.Max(t => t.Age) : 0; //could also return -1
}
This is also possible with a Dictionary
using System.Linq;
public int GetHighestValue(Dictionary<MyTypes, OtherType> obj)
{
return obj.Count > 0 ? obj.Max(t => t.Key.Age) : 0; //could also return -1
}
Simplest is actually just Age.Max(), you don't need any more code.
How about this way:
List<int> myList = new List<int>(){1, 2, 3, 4}; //or any other type
myList.Sort();
int greatestValue = myList[ myList.Count - 1 ];
You basically let the Sort() method to do the job for you instead of writing your own method. Unless you don't want to sort your collection.