"" + Something in C++

How to say if something is in something else c++

You can use the std:: find function to search your array.Suppose your array is arr=["C","X","I"] :
tofind string c="C"
For example your statement will change to:-

  if(find(arr.begin(),arr.end(),c)!=arr.end())
{
//found do something

}

There is no "in" in C++

#define something something in C

As the preprocessor does not know anything about the C language and variables you need to add some definitions know if the variable (variable) will be defined in the C code. You can use those definitions later in the code.

Example:

#if defined(OSCONL)
OSCONL = something;
#endif

And if your microcontroller does not have this register this part of the code will not be compiled. It is a very common technique.

EDIT:

But wouldn't that work the same if it just had #define OSCCONL

The idea is to have the same #define as variable or function name. It makes code consistent and easy to remember.

Otherwise, you would have to have different #define and object name making coding more difficult, as our would have to remember both. In this convention, you can read the documentation of the uC and use the same name to check if this object exists without remembering how the #define is called.

If word then prints something

Try like this :

#include <stdio.h>
#include <string.h>

int main()
{
char x[30];

printf("Enter the noob's name: ");
scanf(" %s",x);

if (strcmp(x,"Bob")==0)
printf("noob\n");
else
printf("pro\n");

return 0;
}

good way to write pointer to something in C/C++

The common C convention is to write T *p, whereas the common C++ convention is to write T* p. Both parse as T (*p); the * is part of the declarator, not the type specifier. It's purely an accident of pointer declaration syntax that you can write it either way.

C (and by extension, C++) declaration syntax is expression-centric; IOW, the form of a declaration should match the form of an expression of the same type in the code.

For example, suppose we had a pointer to int, and we wanted to access that integer value. To do so, we dereference the pointer with the * indirection operator, like so:

x = *p; 

The type of the expression *p is int; thus, it follows that the declaration of p should be

int *p  

The int-ness of p is provided by the type specifier int, but the pointer-ness of p is provided by the declarator *p.

As a slightly more complicated example, suppose we had a pointer to an array of float, and wanted to access the floating point value at the i'th element of the array through the pointer. We dereference the array pointer and subscript the result:

f = (*ap)[i];

The type of the expression (*ap)[i] is float, so it follows that the declaration of the array pointer is

float (*ap)[N];

The float-ness of ap is provided by the type specifier float, but the pointer-ness and array-ness are provided by the declarator (*ap)[N]. Note that in this case the * must explicitly be bound to the identifer; [] has a higher precedence than unary * in both expression and declaration syntax, so float* ap[N] would be parsed as float *(ap[N]), or "array of pointers to float", rather than "pointer to array of float". I suppose you could write that as

float(* ap)[N];

but I'm not sure what the point would be; it doesn't make the type of ap any clearer.

Even better, how about a pointer to a function that returns a pointer to an array of pointer to int:

int *(*(*f)())[N];

Again, at least two of the * operators must explicitly be bound in the declarator; binding the last * to the type specifier, as in

int* (*(*f)())[N];

just indicates confused thinking IMO.

Even though I use it in my own C++ code, and even though I understand why it became popular, the problem I have with the reasoning behind the T* p convention is that it just doesn't apply outside of the simplest of pointer declarations, and it reinforces a simplistic-to-the-point-of-being-wrong view of C and C++ declaration syntax. Yes, the type of p is "pointer to T", but that doesn't change the fact that as far as the language grammar is concerned * binds to the declarator, not the type specifier.

For another case, if the type of a is "N-element array of T", we don't write

T[N] a;

Obviously, the grammar doesn't allow it. Again, the argument just doesn't apply in this case.

EDIT

As Steve points out in the comments, you can use typedefs to hide some of the complexity. For example, you could rewrite

int *(*(*f)())[N];

as something like

typedef int *iptrarr[N];           // iptrarr is an array of pointer to int
typedef iptrarr *arrptrfunc(); // arrptrfunc is a function returning
// a pointer to iptrarr

arrptrfunc *f; // f is a pointer to arrptrfunc

Now you can cleanly apply the T* p convention, declaring f as arrptrfunc* f. I personally am not fond of doing things this way, since it's not necessarily clear from the typedef how f is supposed to be used in an expression, or how to use an object of type arrptrfunc. The non-typedef'd version may be ugly and difficult to read, but at least it tells you everything you need to know up front; you don't have to go digging through all the typedefs.

What does ** do in C language?

In C arguments are passed by values. For example if you have an integer varaible in main

int main( void )
{
int x = 10;
//...

and the following function

void f( int x )
{
x = 20;
printf( "x = %d\n", x );
}

then if you call the function in main like this

f( x );

then the parameter gets the value of variable x in main. However the parameter itself occupies a different extent in memory than the argument. So any changes of the parameter in the function do not influence to the original variable in main because these changes occur in different memory extent.

So how to change the varible in main in the function?

You need to pass a reference to the variable using pointers.

In this case the function declaration will look like

void f( int *px );

and the function definition will be

void f( int *px )
{
*px = 20;
printf( "*px = %d\n", *px );
}

In this case it is the memory extent occupied by the original variable x is changed because within the function we get access to this extent using the pointer

    *px = 20;

Naturally the function must be called in main like

f( &x );

Take into account that the parameter itself that is the pointer px is as usual a local variable of the function. That is the function creates this variable and initializes it with the address of variable x.

Now let's assume that in main you declared a pointer for example the following way

int main( void )
{
int *px = malloc( sizeof( int ) );
//..

And the function defined like

void f( int *px )
{
px = malloc( sizeof( int ) );

printf( "px = %p\n", px );
}

As parameter px is a local variable assigning to it any value does not influence to the original pointer. The function changes a different extent of memory than the extent occupied by the original pointer px in main.

How to change the original pointer in the function?
Just pass it by reference!

For example

f( &px );
//...

void f( int **px )
{
*px = malloc( sizeof( int ) );

printf( "*px = %p\n", *px );
}

In this case the value stored in the original pointer will be changed within the function because the function using dereferencing access the same memory extent where the original pointer was defined.

Is there something in C that is analogous to out/out keyword of C#?

I don't want to return values from the method please

If you don't want to return a value you can do:

void extract_left_subtree(node **right_child)
{
while((*right_child)->right)
{
(*right_child) = (*right_child)->right;
}
printf("rightmost inside the funtion is %d\n", (*right_child)->data);
}

and call it like:

extract_left_subtree(&right_child);

This passes the address of right_child to the function and then the function can directly update the value of right_child

How can I check if an element in an array is equal to something in C?

You did not specify a type for the parameter of your function.

Likely types are int* or char*, but you haven't given enough information to perfectly deduce the type.

bool checkWin(/*You MUST specify a type here!*/ spaceleft)

Example: bool checkWin(int* spaceleft)

How do I check if a variable is not equal to multiple things in C++?

How do I check if a variable is not equal to multiple things

Is the only option to just do:

input != '1' && input != '2' && input != '3' etc etc

In the general case, for an arbitrary set of values: No, that is not the only option, but it is the simplest. And simplest is often best, or at least good enough.

If you dislike the redundant repetition of input !=, a variadic template can be used to generate the expression. I've written an example of this in another question: https://stackoverflow.com/a/51497146/2079303

In specific cases, there may be better alternatives. There exists std::isdigit for example for exactly the particular case in your example code.

In order to check if a variable is (not) equal to mutliple things which are not known until runtime, the typical solution is to use a set data structure, such as std::unordered_set.

How to calculate something in c++?

The problem with your approach is the way how you parse the csv file and store it. Your code creates a queue holding strings for each row and adds all created queues in a vector. This becomes problematic when you now want to iterate through a column.

Try to create a vector for each element you find in the first row. When processing any other row than the first, access the already existing vectors and add the strings. If you follow this approach, you will end up with vectors holding the content of the columns instead of the rows as it stands now. Here is some sample code:

    void readCSV(istream &input, vector<vector<string>>& vOutput)
{
int iRowCnt = 0;
string csvLine;

// read every line from the stream
while( getline(input, csvLine) )
{
int iColCnt = 0;
istringstream inpStreamLine(csvLine);
string strElement;

// read every element from the line that is separated by commas
while( getline(inpStreamLine, strElement, ',') )
{
// if first line, create vector for each column
if (iRowCnt == 0)
{
vector<string> vColumn;
vOutput.push_back(vColumn);
}
// access the vector with index iColCnt and add sub string
vOutput.at(iColCnt).push_back(strElement);
iColCnt++;
}
iRowCnt++;
}
}

void getNumericValues(vector<vector<string>> &vColumns, vector<vector<int>>& vOutput)
{
// iterate across rows (signals)
for (vector< vector<string> >::iterator iterCol = vColumns.begin() ; iterCol != vColumns.end() ; ++iterCol)
{
vector<int> vColumn;
vector<string> *vCol = &(*iterCol);
// iterate across columns (signal values) while skipping first line
// convert strings to integer values and add them to vNumValues
for (vector<string>::iterator iterRow = vCol->begin()+1; iterRow < vCol->end(); ++iterRow)
{
string strElem = *iterRow;
string::size_type sz;
vColumn.push_back(stoi(strElem, &sz));
}
vOutput.push_back(vColumn);
}
}

void getMovingAveragesColumn(vector<int> &vNumValues, int iWndSize, vector<int>& vOutput)
{
if (vNumValues.size()<iWndSize) // check if we have enough values
return;

for (vector<int>::iterator iter = vNumValues.begin() ; iter < vNumValues.end()-iWndSize ; ++iter)
{
int iMovAvg = 0;
for (int ii=0; ii<iWndSize; ii++)
{
iMovAvg+= *(iter+ii);
}
iMovAvg /= iWndSize;
vOutput.push_back(iMovAvg);
}
}

void getMovingAveragesMatrix(vector<vector<int>> &vNumValues, int iWndSize, vector<vector<int>>& vOutput)
{
for (vector<vector<int>>::iterator iterCol = vNumValues.begin() ; iterCol < vNumValues.end() ; ++iterCol)
{
vector<int> *vCol = &(*iterCol);
vector<int> vMovAvg;
getMovingAveragesColumn(*vCol, iWndSize, vMovAvg);
vOutput.push_back(vMovAvg);
}
}

int _tmain(int argc, _TCHAR* argv[])
{
ofstream myfile;
fstream file("c://tmp//test_data.csv", ios::in);
if(!file.is_open())
{
cout << "File not found!\n";
return 1;
}
// vector of vectors for storing strings in matrix form
vector<vector<string>> vData;
readCSV(file, vData);

// convert to integers
vector<vector<int>> vNumValues;
getNumericValues(vData, vNumValues);

// get moving average values
vector<vector<int>> vMovAverages;
getMovingAveragesMatrix(vNumValues, 3, vMovAverages);

// print the moving average values
for (vector<vector<int>>::iterator iterCol = vMovAverages.begin() ; iterCol < vMovAverages.end() ; ++iterCol)
{
vector<int> *vCol = &(*iterCol);
for (vector<int>::iterator iterRow= vCol->begin() ; iterRow < vCol->end() ; ++iterRow)
{
cout<< *iterRow << " ";
}
cout<<"\n";
}

myfile.close();
system("pause");
}

Way to check if the variable is value of something

The || operator performs a logical OR between its two operands. It evaluates to 1 if either operand is non-zero. In the case of 1 || 5 This evaluates to 1 because at least one operand is non-zero. This evaluation continues on for each successive || operator.

So the whole expression (1 || 5 || 7 || 8 || 11 || 20) is equal to 1.

Your original check is the proper way to do this. If you want something a bit less repetitive, you could do this with a switch statement with fallthrough cases:

switch (m) {
case 1:
case 5:
case 7:
case 8:
case 11:
case 20:
printf("true\n");
break;
default:
printf("false\n");
break;
}


Related Topics



Leave a reply



Submit