C++ :: Interesting Use Of Auto To Make Foreach Macro

Jul 23, 2014

I thought I'd display my fun use of the new C++11 auto keyword to create a compile time foreach. It only works for STL collections, or anything that implements the STL collection iterator methods begin(), end() that return a STL iterator.

// Standard Template Library foreach
// element = iterator name
// collection = STL data collection variable
#define stl_foreach(element, collection)
for(auto element = collection.begin(), __end__ = collection.end();
element != __end__; element++)
}

[code]....

View 2 Replies


ADVERTISEMENT

C++ :: How To Generate Auto ID (or Auto Number)

Feb 16, 2012

This code is for (hospital management system).

This code allow you to add patients.

There are two types of patients. which is:
1. Normal patient.
2. Critically ill patient.

once you added any patient. You will be able to show all patient using "ShowAllPatient;" method. -> i want the Auto-increment ID Number to appear for each patient has been added.

And you will be able to call a patient to provide a hospital services for him/her using "GetNextPatient;" method.

I need to generate an Auto-increment Number for each (patient) has been added. (Auto-increment Number) but it just should be different for each patient. For example the first patient will have 1, The second patient will have 2. etc. The Auto-increment number should appear for each patient.

View 14 Replies View Related

C++ :: Selection Of Interesting Point From Long List

Mar 29, 2013

I have some codes which are not efficient enough to get the answer faster.

Q: Tom is looking for a car with high miles per gallon and high horse power.For example:P1--Toyota with MPG=51,HP=134, the P2--Honda with MPG=40,HP=110, P3--Ford Fusion with MPG=41,HP=191,P4--Nissan with MPG=35,HP=195,P5--Volkswagen with MPG=30,HP=140

Since,p2 is worse than p1(in terms of MPG,HP) and p5 worse than p4(MPG,HP), thus they are cancelled. The leftover 3 cars are considered interesting cars.Tom wish to find all interesting cars from the list but there's too many of them. Thus write a program to find this list as fast as possible.(C++)

int SimpleAlgo2 (int &n, int &d, vector< vector<float> > &point) {
vector<bool> isBest(n+10, true);
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {

// We will check if point[i] is strictly worse than point[j]
// no need to check if we already know that point[i] is not the best
if (isBest[i]) {

[Code] ....

View 3 Replies View Related

C++ :: Define A Macro Within A Macro?

Feb 26, 2012

Is it possible to define a macro with in a macro? Any trick will do. I am trying to do quick conversion of cuda program to open mp by defining some macros at the top:

Code:
#define __syncthreads() #pragma omp barrier

View 2 Replies View Related

C# :: Using Foreach Loop To Select A Name In Queue

Mar 13, 2015

I know that where I have the intIndex++ line is wrong. It's just going to stop at the last index and call it good, but I don't know how to make it stop at the matching name. The only examples I can ever seem to find use the foreach loop to print out a value, and I'm clearly just not understanding this enough to make it work for me.

Instructions are:
--Declare a variable to store the result of the search, int intIndex;
--Use an if statement with the Contains method to check if the name in the search box is in the queue.
--If Contains is true, initialize intIndex to zero and use a foreach to walk through queue, else display a message that the name is not in the list.
--If a match is found use intIndex to select the matching entry in listbox and display a message indicating the name was found. Be sure to increment intIndex each time through the loop.

private void btnSearchByName_Click(object sender, EventArgs e) {
//delcare int variable to use as the index for the list box
int intIndex;
//If Contains is true
if (cstrName.Contains(txtSearchName.Text))

[Code] .....

View 5 Replies View Related

C# :: Foreach And Modifying Objects In Collection

May 8, 2014

I have a class that loads the contents of a XML file into their respective object types and stores those objects in a list. Each object has its own list of objects with properties the program will later modify.

The problem I am currently having is that after looping through the objects and modifying the necessary properties the modifications do not persist. This leads me to believe I am modifying a copy of the object rather than the object I think I am modifying. I am not sure why this is happening as I believe I should be modifying the object that is referenced in the collection.

What I have tried, I started using LINQ to get the object I am looking to modify. After a little more research I don't think this can work properly due to the LINQ query returning a new object(copy of the object). Currently I am using nested foreach loops which still are not behaving the way I expect as the properties I am setting are not making their way back to the original object.

The PopulateLogSheet() in the following class is where the problem loop is.

class ChillerCheckCollection {
public List<Chiller> chillers = new List<Chiller>();
public void LoadChillers(string filePath) {
var availableChillers = (from chiller in Xdocument.Load(filePath).Descendants("chiller")
select new Chiller

[Code] ....

And here are the other classes referenced in the above class.

class Chiller {
public IEnumerable<LogSheet> chillerLogSheet = new List<LogSheet>();
public int chillerID;

[Code] ....

View 2 Replies View Related

C# :: Creating Multiple Labels In Foreach Loop

Apr 29, 2015

I am attempting to create multiple labels in a for each loop for each tag text (using htmlagility pack). My current code only creates one and doesn't change the first value (Which is AAE). I am using the labels to later input all the label.text into a database after the initial loop has finished (not shown).

foreach (var tag in tdTags) {
MessageBox.Show(tag.InnerHtml);
Label label = new Label();
label.Name = "contentName" + tag.InnerHtml;
label.Text = tag.InnerHtml;

[Code] ....

View 3 Replies View Related

C Sharp :: ForEach Loop Logic Using KeyValuePairs

Jun 3, 2013

I'm new to C#. I'm trying to create a program to audit some of our processors. As you will see below, I have two foreach loops that allow me access to errorOrders(returns <<UserName, #of errors>>) and totalOrders (returns <<UserName, #of totalOrders>>).

However, the problem i'm running into now is that it seems to constantly loop through these two ForEach loops. When i run it, the 'count' on both errorOrders & totalOrders is 38. The program loops through all 38 users just fine, but then it continues to loop through users again...re-doing the process that it just finished.

I'm looking to see if there is another way I could set this section up so that it only loops through users once. I was thinking about trying to create a 'Boolean flag' that would force the program out of the ForEach loop after it has run through all the users...but i'm sure there are other ways to handle this.

foreach (KeyValuePair<string, int> error in errorOrders)
{
foreach (KeyValuePair<string, int> total in totalOrders)
{  

[Code]....

I know i should probably seperate these two foreach loops instead of having them nested..however, the problem that arises once i do that is my errPercentage can not be calculated if i do.

View 1 Replies View Related

C :: Defining And Using A Macro

Jan 4, 2015

I am trying to create a small set of filepath functions that I intend to compile across linux and windows (I prefer not to use a big library). I want to have a global constant PATH_SEPARATOR that depends on the OS environment. This is what I set at the top of header file.

Code:

#include <stdio.h>
const char PATH_SEPARATOR =
#ifdef _WIN32
'';
#else
'/';
#endif I was hoping to test this while compiling this in a linux environment using gcc, thusly:

Code:

int main (int argc, char const* argv[])
}

[code]....

where apparently, I seem not to be able to "set" a part of the code to have "_WIN32" defined. I don't know if I explained this clearly.

View 5 Replies View Related

C++ :: Macro To Template?

Mar 22, 2013

I have this macro, that expands to some methods of my class:

Code:
#define POPULAR_COMBO_FILTRO_COM_BASE(classeTabela)
void VisualizadorLogsFrame::PopularComboFiltroCom ## classeTabela (bool limparTexto) {
long from, to;
m_cbxDetalhe->GetSelection(&from, &to);

[Code]...

but I get a compile error on this line:

Code:
for (list< CLASSE_TABELA *>::iterator linha = lista->begin(); linha != lista->end(); linha++) {

what am I doing wrong ? the error is:

VisualizadorLogsMain.h:174: error: expected ';' before 'linha'
VisualizadorLogsMain.h:174: error: 'linha' was not declared in this scope

View 4 Replies View Related

C :: Variadic Macro Function

Sep 12, 2013

I'm doing right now is creating a function that callocs (I prefer this to malloc) and returns a string, and it will work similar to printf, I'm calling the function alloCpy(),I have several values that I need in a malloced string, so I call Code: myAllocedString = alloCpy("Value 1 is %s, value 2 is %s, and value 3 is %d", str1, str2, num); To do this I'm using the Variadic Macro, the reason I'm not just using a Variadic Function such as this: Code: char* alloCpy(char *format, ...) {} is because I need to append NULL to the end for the sake of looping through arguments, and I'm understanding it thusfar, but I have a few issues, first of all, I tried defining the Macro in a header file, but when I try to call it I get the error "Undefined reference to alloCpy". Also, to loop through arguments to get string lengths I'm using va_arg(args, char*) which requires all the arguments to be of type char*. Here is my code:
myheader.h:

Code:

#define alloCpy(format, ...) _alloCpy(format, ##__VA_ARGS__, NULL);
char* _alloCpy(char *format, ...); mycfile.c: Code: char* _alloCpy(char *format, ...) {
va_list args;
va_start(args, format);
int args_len = 0;
}

[code]....

So, how can I do this to, first of all, make my macro function accessible from other files importing myheader.h, and second, how can I make it accept any type of argument like printf, so that my example above would work?

View 3 Replies View Related

C :: Testing If A Macro Is Defined To A Value?

Jan 16, 2015

Say I have something lke

Code:
#define FOO BAR
#if FOO == BAR
doX();
#else
doY();
#endif

This causes doX(); to be executed. But the intent is to have doY(); be run. I'm guessing this is because BAR is undefined and therefore blank, so blank equals blank. Is there some way to compare the symbol FOO was set to instead of its value, BAR?

View 4 Replies View Related

C++ :: Replacing Macro With Constant

Apr 4, 2013

I heard that const shall be preferred over #define . So I start to change my program accordingly.

But then below error message occurs during compilation:

#include "common.h"
#include "definition.h"
#include "particle.h"
int main() {
Particle *p = new Particle();

[Code] .....

I guess the error occurs because, when the line 9 of particle.h (File 4) is compiled, value of const int dimension is not seen by the compiler.

View 6 Replies View Related

C/C++ :: Migration Of Serialization Macro

Jun 12, 2014

I have to migrate C++ source which is compiled with MinGW-gcc to be compiled with VS2013, and have one issue with one macro used for serialization.

Here is macro:

#define IMPLEMENT_SERIALIZE(statements)
unsigned int GetSerializeSize(int nType, int nVersion) const
{
CSerActionGetSerializeSize ser_action;
const bool fGetSize = true;

[Code] ....

Here is place in code were it is call (in class declaration):

IMPLEMENT_SERIALIZE(({
if (!fRead) {
uint64 nVal = CompressAmount(txout.nValue);
READWRITE(VARINT(nVal));

[Code] .....

When compile received errors:

main.h(555): error C2059: syntax error : '{'
main.h(555): error C2143: syntax error : missing ';' before '{'
line 555 is end of macro call ( "})").

How should look using of this macro in order to avoid that errors?

View 7 Replies View Related

C++ :: Pitfalls Of Macro Substitution?

Dec 29, 2013

"If you examine the expansion of max, you will notice some pitfalls. The expressions are evaluated twice; this is bad if they involve side effects like increment operators or input and output. For instance, the below example will increment the larger twice."

#define max(A, B) ((A) > (B) ? (A) : (B))

max(i++, j++)/* WRONG */

I don't see what the problem is with the code above. i is incremented and j is incremented and then it performs a ternary operation to see which is greater. Am I missing something?

View 1 Replies View Related

C++ :: Two Projects - Defining Value Of Macro

Jun 27, 2012

Say I have two projects A and B. A depends on B. If project A defines a macro to be 100 and project B defines the same macro to be 200. In project A, if I use this macro, what value would this macro be? Let's just forget macro is evil for the time being. Let's also forget that it is not good to define the same macro twice for the time being.

View 8 Replies View Related

C :: How Macro Works To Concatenate Three Integers

Nov 15, 2014

when i was finding a way to concatenate three integers in C, I came across a snippet like this

Code:

#include<stdio.h>
#define cat(a,b,c) a##b##c
int main()
{
int d;
d=cat(1,2,3);
return 0;
}

How the macro works here? I am unable to understand the function '#' plays in the macro.

View 1 Replies View Related

C :: Writing A Macro That Returns A Boolean Value

Apr 24, 2014

I need writing a macro that would return true/false (1/0) )value. I want to check if a certain element exists in the array. The macro will accept array, its size, and the value to be compared, and must return yes or no. Here is the code that I have written:

Code:
#define EXISTS(T, a, n, val) do {
char ret=0;
T *a_ = (a);
size_t n_ = (n);
for (; n_ > 0; --n_, ++a_){
ret = (*a_ == val);
}
}
while(0)

How can I get the result from this macro.

View 6 Replies View Related

C++ :: Macro For Changing Array Size

Nov 22, 2013

I'm trying building a new macro for change the array size:

#define redim(varname,x) ((sizeof(varname)*) realloc (varname, x * sizeof(varname)));
int b;
redim(b,3);

error message:
"error: expected primary-expression before ')' token"

what isn't right with these macro?

View 10 Replies View Related

C++ :: Linking To Static Library That Contains A Macro

Jul 16, 2014

I have built a static library that contains a macro. From a separate exe, I am calling this macro, but it doesn't work.

The compilation of the static library and that of the exe went okay.

Static lib contains just the macro definition.

Exe contains call to this macro.

Is there anything else that I need to do for this to work?

View 4 Replies View Related

C# :: Command To Attach A Macro On A Process?

Jan 20, 2014

i would like to know if its possible to use a c# command to attach a macro ( JitBix MacroRecorder ) so it would send keystrokes while the process/program was minimized. i've tried with [lapeiro, on 20 January 2014 - 06:43 AM, said: i would like to know if its possible to use a c# command to attach a macro ( JitBix MacroRecorder ) so it would send keystrokes while the process/program was minimized.

View 4 Replies View Related

C++ :: Adding Char Array With Macro?

Dec 30, 2013

The book uses this example:

#define ALLOCSIZE 10000 /* size of available space */
static char allocbuf[ALLOCSIZE]; /* storage for alloc */
static char *allocp = allocbuf; /* next free position */
char *alloc(int n)
/* return pointer to n characters */

[Code] ....

The logic here I don't understand:

if (allocbuf + ALLOCSIZE - allocp >= n)

allocbuf is a char array allocated with 10000 positions. We add that to ALLOCSIZE macro which is 10000. Does that return a value of 20000? If so, it doesn't make sense to do this because all we had to do was this:

if (allocbuf - allocp >= n)

That takes length of allocbuf which is 10000 and subtracts allocp from it. So if allocp is 1000 we are left with 9000 available slots. And we can use that to check if we have enough to allocate n elements.

View 5 Replies View Related

Visual C++ :: Using Macro To Generate DEF File

Nov 30, 2012

I'm trying to build libglib using MSVC. libglib doesn't use dllexport - so to create usable DLLs it needs to generate a .DEF file. It does this by using a .symbols file. Here's a cut-down example:-

Code:
/* This file lists all exported symbols. It is used to generate the glib.def file used to control exports on Windows.*/

/* glib.symbols */
g_mkdir_with_parents

#ifdef G_OS_WIN32
g_file_get_contents_utf8
#endif

The following commands would produce the following files called glib.def

Code:
cl /EP glib.symbols > glib.def

produces this in glib.def:-
g_mkdir_with_parents

Code:
whereas this:-
cl /EP -DG_OS_WIN32 glib.symbols > glib.def

produces this in glib.def:-
g_mkdir_with_parents
g_file_get_contents_utf8

So this is a handy way of producing conditional .DEF files. Fortunately, this can all be built into a Visual Studio macro in my vsprops file - e.g.

Code:
<UserMacro
Name="GlibGenerateGlibDef"
Value="echo >"$(SolutionDir)glib.def" && cl /EP -DG_OS_WIN32 glib.symbols >>"$(SolutionDir)glib.def""
/>

Problem:- Although I can run the macro as a pre-build step (and it does produce conditional entries in the generated .DEF file) it DOESN'T produce the word EXPORTS at the top of the file. So the linker then fails to recognise it as a valid .DEF file.

How can I add that word EXPORTS to the top of the generated file? I tried just adding EXPORTS to the top of the symbols file but that didn't work. I also tried this variation on the macro:-

Code:
Name="GlibGenerateGlibDef"
Value="echo EXPORTS >"$(SolutionDir)glib.def" && cl /EP -DG_OS_WIN32 glib.symbols

But that didn't work either I feel sure there must be a way to do this.

View 1 Replies View Related

C++ :: Macro For Debugging New Through Operator New Syntax?

Aug 14, 2013

It's common to see the following macros:

Code:
#define DEBUG_NEW new(__FILE__, __LINE__)
#define new DEBUG_NEW

and overloading operator new for debugging purposes. It usually works but there is a problem when use operator new syntax in code instead of directly use new. I can change my code but i can't change third party's code. Something like this:

Code:
int* j = static_cast<int*>(::operator new(sizeof(int)));

It's not common, but it appears occassionally.With that syntax, new macro generates compilation errors.

Is there any way to fix this problem?

View 2 Replies View Related

Visual C++ :: Macro With Multiple Parameters

Oct 22, 2014

In the following example, SET_DARKENING_PARAMETERS_0 is a fairly simple macro which accepts 9 parameters. The first one is called driver and the other 8 are all ints. Basically, the 8 x ints get assigned to the first 8 elements of an array which is owned by driver. I can call the macro successfully if I do this:-

Code: SET_DARKENING_PARAMETERS_0 ( some_driver, 500, 400, 1000, 275, 1667, 275, 2333, 0 );

But in the actual code I'm trying to compile, the 8 x ints are themselves encoded into a secondary macro like this:-

Code: #define CONFIG_OPTION_DARKENING_PARAMETERS 500, 400, 1000, 275, 1667, 275, 2333, 0

So the actual code (to call SET_DARKENING_PARAMETERS_0) looks like this:-

Code: SET_DARKENING_PARAMETERS_0 ( some_driver, CONFIG_OPTION_DARKENING_PARAMETERS );

But the two combined macros won't compile with VC8. Basically, I get warning #C4003 (not enough parameters for macro 'SET_DARKENING_PARAMETERS_0') followed by a load of syntax errors. However, the code (allegedly) compiles with gcc.

I'm wondering if macro CONFIG_OPTION_DARKENING_PARAMETERS might be getting truncated to just 500, (with the following parameters getting ignored)?

View 5 Replies View Related

C++ :: Auto Align CPP File

Apr 20, 2014

Is there a way to auto align a cpp file?

View 7 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved