Friday, April 29, 2011

A project with output type of class library cannot be started directly - with a startup exe

Firstly I'm completely aware of this message and why it happens normally. It's not that I'm just trying to run a dll (like this question).

I have a project that compiles to a dll but has a startup program specified in the project properties. Most of the time I'm able to right-click on the project and select Debug > Start new instance, and it will run the program and let me debug my dll. However, occasionally I get this message (A project with output type of class library cannot be started directly) as if I haven't got a startup program. The first few times I thought it was just me accidentally clicking on the wrong project but I'm certain this isn't the case given that it's happened so many times and I've been careful to watch it.

When this message appears I'm able to try it again and it always works on the second or third attempt.

A colleague using the same Solution never has this problem :-/

Anyone else had this problem or know how to solve it?

I'm using Visual Studio 2005 Pro Version 8.0.50727.762 (SP.050727-7600)

From stackoverflow
  • This sounds like a transient Visual Studio problem. Reinstallation or upgrade may solve your problem.

  • Typically problems in VS are caused by:

    • Add-ins: Run VS without and see if the problems is solved
    • Corrupted files in your solution: Delete / rename all files created by Visual Studio which are not part of your project, i.e. all .suo, .ncb files and a like.
    Pedro : +1 for the deletion of the .suo file. That often fixes problems for me (especially with breakpoints that disappear or reappear for no reason.)
  • I had this problem with projects that were created as "Windows Control Library" that somehow forget their status. Unloading and reloading the project usually did the trick.

    If it was created as a "Class Library" then to make it a "Windows Control Library" I manually add the following to the .csproj file. It was the only difference I could see between a class library and windows control library project.

    BTW - starting a Windows Control Library starts the User Control Test Container - allows you to test any user control in the library. Very cool.

    <Service Include="{94E38DFF-614B-4cbd-B67C-F211BB35CE8B}" />
    

    add that inside of an <itemgroup> element.

  • no just make a start up project

  • Another colleague suggested it's because after clicking Debug > Start new instance, while I'm waiting for it to start up, I click on a different project. I don't do it for any reason, just randomly selecting things as I wait for the project to start up. Maybe Visual Studio looks at the selected project sometime after I clicked the menu, gets confused, and shows the error message?

    Anyone able to confirm this matches their experience?

Mix XML Parents and Children in MSSQL

I think what I need is CROSS APPLY, but I can't seem to figure out the syntax. I have a set of XML in an MSSQL 2008 database that looks like this:

<Cookie>
   <id>Chocolate Chip</id>
   <ChocolateChipPeanutButter>
      ...
   </ChocolateChipPeanutButter>

   <ChocolateChipPecan>
      ...
   </ChocolateChipPecan>
</Cookie>

<Cookie>
   <id>Raisin</id>
</Cookie>

<Cookie>
   <id>Coconut</id>
</Cookie>

<Cookie>
   <id>Sugar</id>
</Cookie>

I'm trying to chop the XML up so that I have a result set that looks like this:

Cookie Name                   Cookie SubName
___________                   ______________
Chocolate Chip                <null>
Chocolate Chip                ChocolateChipPeanutButter
Chocolate Chip                ChocolateChipPecan
Raisin                        <null>
Coconut                       <null>
Sugar                         <null>

I think I need to write something like this (assume the XML data is stored in DECLARE @XMLData XML :

SELECT
     TheXML.TheCookie.query('data(./id)')     AS CookieName
   , TheXML.TheCookie.query('.')              AS CookieData
   , Sub.SubCookieName                        AS SubCookieName
FROM
   @XMLData.nodes('//Cookie') AS TheXML(TheCookie)
CROSS APPLY
   (
       SELECT
          TheCookieXML.SubCookieName.query('local-name(.)')
       FROM
          CookieData.nodes('./*') AS TheCookieXML(SubCookieName)
   )

I know, I know, this XML schema is terrible for what I'm trying to do with it, but lets assume that we're stuck with the data this way and work from there. Am I on the right track? Will CROSS APPLY ever work like this? Can even Batman save me now?

From stackoverflow
  • Try something like this:

    SELECT
         TheXML.TheCookie.value('(id[1])', 'varchar(20)') AS CookieName
       , TheXML.TheCookie.query('.') AS CookieData
       , Sub.SubCookie.value('local-name(.)', 'varchar(20)') AS SubCookieName
    FROM
       @xmlcon.nodes('//Cookie') AS TheXML(TheCookie)
    CROSS APPLY
        TheXML.TheCookie.nodes('./*') as Sub(SubCookie)
    

    Trouble is - this also selects the "id" node :-(

    Marc

    Tomalak : TheXML.TheCookie.nodes('./*[local-name() != 'id']) as Sub(SubCookie)
    brian : perfect, thanks guys!
    Tomalak : Third attempt of a comment... The above contains some single quote glitches, nothing serious. Alternative, simpler XPath: TheXML.TheCookie.nodes('./*[not(self::id)]')
    marc_s : Excellent comment, Tomalak! Thanks - nice technique for excluding nodes!
    brian : Tomalak, that XPATH was very helpful, I wish you could get rep from votes on comments.
    Tomalak : @brian: Glad to help. Virtual rep is also accepted. :-D
    Tomalak : @marc_s: Oh, I nearly forgot. +1 for the answer.

Apply Multiple CSS classes on an HTML element (jQuery addClass)

Given this HTML:

<html>
<head>
  <style type="text/css">
    tr.Class1
    {
      background-color: Blue;
    }
    .Class2
    {
      background-color: Red;
    }
  </style>
</head>
<body>
  <table>
    <tr id="tr1">
      <td>Row 1</td>
    </tr>
    <tr id="tr2">
      <td>Row 2</td>
    </tr>
  </table>
</body>
</html>

Below is the script secion. What will happen when I click on the first row? Will it remain blue, or will it turn red? If it will remain blue, how do I get it to turn red instead WITHOUT removing the Class1 class from the row (so I can remove the Class2 class later and the row will return to its original color of blue)?

<script type="text/javascript" language="javascript">

  $(document).ready(function() {
    $("#tr1").addClass("Class1");

    $("tr").click(function() {
      /* clicked tr's should use the Class2 class to indicate selection, but only one should be selected at a time */

      $(".Class2").removeClass("Class2");
      $(this).addClass("Class2");
    });
  });

</script>

Edit I should say - I tried this, and it's not working as expected (in either FireFox or IE). What is going on?

From stackoverflow
  • It should turn red...that's why it's called cascading style sheets...new additions to the properties override older ones.

    Brandon Montgomery : I know, but I'm not getting that behavior.
  • Mozilla says here:

    If the same property is declared in both rules, the conflict is resolved first through specificity, then according to the order of the CSS declarations. The order of classes in the class attribute is not relevant.

    But this isn't the behavior I'm getting.

  • try this:

     $("tr").click(function() {
      /* clicked tr's should use the Class2 class to indicate selection, but only one  should be selected at a time */
    
      $(".Class2").removeClass("Class2");
      $(this).toggleClass("Class1");
      $(this).addClass("Class2");
      $(this).toggleClass("Class1");
    });
    

    I don't know if it will work but maybe it will give you more into the problem.

  • Figured it out. I put my example up a little incorrectly. The CSS actually looked like:

    tr.Class1
    {
      background-color: Blue;
    }
    .Class2
    {
      background-color: Red;
    }
    

    Therefore, the most specific rule applies, just like Mozilla told me here:

    If the same property is declared in both rules, the conflict is resolved first through specificity, then according to the order of the CSS declarations. The order of classes in the class attribute is not relevant.

oracle jdbc driver version madness

Why the heck does Oracle offer a different(!) version of the JDBC driver, e.g. ojdbc14.jar, for every(!) database version?
The files all have different sizes and thus probably different content.

background:
We get a random and seemingly irreproducible error saying "invalid number" when saving data (we guess it's the Timestamp). But it's not any particular statement. Most of the time, it saves just fine. Just once a month a harmless looking statement will fail.

So i had a closer look at Oracle's download site and noticed that none of the filesizes match despite files sharing the same name.

Our product is run on databases maintained by our clients, i.e. whatever version and patch the clients have running is what it is.
So what driver do we use? The latest (Oracle 11g) - despite the fact that it's usually 9i and 10g databases?

Why don't they just link all versions to the same "one driver suits all" file?
Or are there minute differences leading to effects like our random errors?

EDIT: i was mistaken about the 9i databases.

From stackoverflow
  • please see the compatibility matrix at http://www.oracle.com/technology/tech/java/sqlj_jdbc/htdocs/jdbc_faq.html#02_02

    Also take in mind that the timestamp datatype is only available since Oracle 10.

    Stroboskop : These drivers "can talk to" just about any modern database version. So you're saying i just pick the newest release and keep my fingers crossed that it has all the bug fixes i need? ... and i was wrong about the 9i's. We retired them last year.
    Oliver Michels : well, i doubt it is a bug in the jdbc driver. i would inspect the code for number casting bugs, "number to string", "string to date" and so on. Are we talking about ORA-01722, invalid number? If so, i would check the debugging logs and not care about driver version conflicts.
    Stroboskop : Yes, it's ORA-01722. We use PreparedStatements, meaning the type conversions are all done by the driver. And the same statement works fine 99.9% of the time. We of course looked at our code first, but there seems to be nothing out of the ordinary.
  • When we upgraded our Oracle database from 8.1.7 to 10.2.0, I was able to use the same Oracle jdbc driver (ojdbc14.jar). So their jdbc driver supports quite a few versions at the same time. Of course it's possible that some of the drivers are buggy, but the plan is to support more versions at the same time.

issue of virtual method in C#

Hello everyone,

In MSDN, it is mentioned,

http://msdn.microsoft.com/en-us/library/9fkccyh4(VS.80).aspx

I am confused what does this item mean "A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier."?

(this is the 2nd differences between virtual and abstract)

thanks in advance, George

From stackoverflow
  • Can you explain what's confusing about it? Properties can be overridden like any other method.

    public class Base {
      public virtual int Prop1 { get { ... } set { ... } }
    }
    
    public class Derived : Base {
      public override int Prop1 { get { ... } set { ... } }
    
    George2 : My confusion is not overridden property, but why it is a differences between abstract and virtual -- ""A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier."? Please see the context of MSDN I quoted.
    Tor Haugen : Abstract members have no implementation, and so _must_ be overridden. Virtual members have an implementation, and _may_ be overridden. That's the difference.
    George2 : Understand, MSDN words are so fuzzy. :-)
    Coincoin : I don't think this is what the doc meant, or if it did, it's a very bad choice of words. Still, it's the best explanation. The writer was probably just past the Ballmer peak. Yay MSDN!
  • If you declare a method virtual in your base class you can override it in your derived class.

    Example

    class MyBaseClass
    {
       public virtual void MyOverridableMethod()
       {
              ...
       }
    
    }
    
    class MyDerivedClass : MyBaseClass
    {
       public override void MyOverridableMethod()
       {
             ...
       }
    }
    

    Notice the override modifier in MyDerivedClass.

    George2 : My confusion is what is the differences between abstract and virtual in the quoted words -- " virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier"?
  • The only difference between virtual and abstract, is that an abstract method or propery has no implementation in the class where it has been defined (the abstract class), and that it must be overriden in a subclass; whereas a virtual method or property has an implementation in the class where it has been defined, and so it is not mandatory to override it in a subclass.

    public abstract AbstractClass { // This class cannot be instantiated, since it is // abstract, and the class is abstract because // it has an abstract member

    public abstract MyProperty {get; set; }
    

    }

    In a class where you derive from AbstractClass (the above AbstractClass is just for explanation purposes; since it has no methods / properies that have an implementation, you could create an interface instead of an abstract class), you will have to provide an implementation of MyProperty. Otherwise, it won't compile. You do this by 'overriding' the MyProperty, you don't want to introduce a new member, but just provide an implementation for a property that has been defined previously.

    public class ConcreteClass : AbstractClass
    {
        public override MyProperty {
           get
           {
                return _someValue;
           }
           set
           {
                if( _someValue != value ) _someValue = value;
           }
    }
    
    George2 : So, you think MSDN means, for abstract base class, it is "must", but for non-abstract base class, it is "can" (not a must)?
    Frederik Gheysels : It is defenitly a must; try to inherit from an abstract class, and don't override an abstract method or property; the compiler will complain.
  • Okay, let's say you have a base class, and that that base class is, itself, derived from another class.

    public class Bar : Foo
    {
       virtual public int SomeProperty { get; set; }
    }
    

    What the virtual keyword means is that in a class derived from Bar, you can override SomeProperty to change its behavior:

    public class Baz : Bar
    {
       private int thisInt;
       override public int SomeProperty 
       {
          get { return thisInt; }
          set 
          {
             if(value < 0)
             {
                throw new ArgumentException("Value must be greater than or equal to zero.");
             }
             thisInt = 0;
          }
       }
    }
    

    Clarification: When an object of type Baz is used, its version of SomeProperty is invoked, unless the type is cast to Bar. If you define Baz's SomeProperty as virtual, classes derived from Baz can also override it (in fact, that may be required--can't recall right off the top of my head).

    Further Clarification: An abstract method has no implementation; when you add one to your class, you must also mark the class as abstract, and you cannot instantiate new instances of it, like this:

    MyAbstractType m = new MyAbstractType();
    

    Virtual members, on the other hand, can have an implementation (like SomeProperty, above), so you don't have to mark the class abstract, and you can instantiate them.

    George2 : Thanks Mike, you answered well but not what I am asking. My question is answered by Tor Haugen, and you can refer there. It is my fault that I do not make myself understood.
    Frederik Gheysels : It is not required to override virtual members.
    Mike Hofer : @George: I clarified the answer to accomodate your question. @Frederik: Note that I said that "you can override" a virtual member.
    Frederik Gheysels : @Mike: I was referring to this sentence of yours: In fact, that may be required--can't recall right off the top of my head
    Mike Hofer : @Frederik: Of course, you're right. I think I was trying to say something else. Way too early in the morning at that time, and I have no idea why I was trying to write that before enough coffee. :) Thanks for the clarification.
    Mike Hofer : Would someone care to explain the downvote? If I'm wrong, please point out where, and enlighten me. I'd rather learn than be left in the dark. Seriously.
  • I can understand the confusion. I have been there before, so I'll share how I keep the basic differences straight...

    virtual vs. abstract:

    • If a class method (or property) is marked virtual, then it may be overridden using the override keyword, if you choose to inherit (aka derive) from that class.

      The virtual keyword is intended to evoke the idea that the method may or may not be the actual method called. Therefore, I always think of virtual members as default implementations, meaning that it represents functionality that can be generalized, such as an Eat() method on a Human class, which might involve eating with one's hands. However, a ChineseHuman class might override the default implementation of Eat(), in order to allow for an implementation that uses chop sticks instead. Finally, because virtual methods and properties are default implementations, the class that defines that member must provide a complete implementation of the method or property. All Human objects must know how to Eat().

      An object-oriented way of thinking might declare that virtual members represent instincts. To Eat() is an instinct of a Human class object. A ChineseHuman may learn to Eat() with chop sticks.

    • If a class method (or property) is marked abstract, then it must be overridden using the override keyword, if you choose to inherit from that class.

      The abstract keyword is intended to evoke the idea that the class only supports the capability represented by the member, and that there is not any common logic that can be generalized for that feature. In other words, abstract members are only conceptual, and therefore they lack an implementation. It is a little confusing that C# asks us to override abstract members when we implement an inheritance relationship, but in this case it really means that we are overriding the empty concept with a concrete implementation. An example of an abstract member of a Human class might be Speak(). There would not be a common way of speaking for all Human objects, nor is it instinctual, because it requires language to express. Note: Some might argue that Speak() belongs on an interface instead.

      An object-oriented way of thinking might declare that abstract members represent behavior (methods) to be learned and knowledge or beliefs (properties) to be acquired. To Speak() is a learned behavior of a Human class object. A ChineseHuman may learn to Speak() differently than an EnglishHuman and neither knows how to Speak() just because they are both Human.

    Nuances:

    • virtual methods do NOT need to be overridden.
    • There is no such thing as a virtual class.
    • abstract members can only appear on abstract classes. In the above examples, having an abstract method on the Human class implies that Human is an abstract class, and that, therefore, a Human cannot be instantiated using the phrase var baby = new Human();. Instead, the BabyHuman class should inherit from Human, and it should be instantiated as var baby = new BabyHuman();. Because a BabyHuman() is a Human and EnglishHuman and ChineseHuman both also inherit from Human, EnglishHuman could inherit from BabyHuman instead of Human. Being Human is abstract because we are all something more than simply Human.
    • abstract members cannot be hidden, only their override implementations may be (further up the inheritance chain). For example, BabyHuman must implement the abstract Speak() method as an override. If EnglishHuman inherits from BabyHuman, it may then hide the BabyHuman implementation of Speak() with its own implementation by using the new keyword (see "Method Hiding in C#" reference below).
    • abstract classes can have virtual members. That's a main distinction between an interface and an abstract class. In that sense, an abstract class can define both a contract and a template of the class' behavior, whereas an interface only defines a contract.

    Code Reference:

Using VBA to parse text in an MS Word document

Hi, I was hoping someone could help with a MS Word Macro.

Basically, I have a MS Word document which lists out several text files and specific pages of interest in each file.

The file format is similar to:

textdocument1.txt              P. 6, 12 - issue1
textdocument2.txt              P. 5 - issue1
                               P. 13, 17 - issue3
textdocument3.txt              P. 10

I want to read each line into my Macro as a string.

Then traverse through it to identify the file name. With the file name, I can then open the file, go to the page number, and copy the data I need.

But I'm stuck at step 1, how do I capture the line into a string in an MS Word Macro?

Any help will be appreciated.

From stackoverflow
  • If your word document lists all the text files like this:

    <name>{tab}<page ref>{newline}
    <name>{tab}<page ref>{newline}
    <name>{tab}<page ref>{newline}
    

    Then all the lines are available in the Paragraphs collection. You can loop through that with a simple For Each loop:

    Dim p As Paragraph
    
    For Each p In ActiveDocument.Paragraphs
      Debug.Print p.Range.Text
    Next p
    
  • The following code should get you started:

    Public Sub ParseLines()
        Dim singleLine As Paragraph
        Dim lineText As String
    
        For Each singleLine In ActiveDocument.Paragraphs
            lineText = singleLine.Range.Text
    
            '// parse the text here...
    
        Next singleLine
    End Sub
    

    I found the basic algorithm in this article.

    Anonymous Type : This will break the document up into paragraphs. If you want sentences do this per line (i.e. sentence) check my answer below.
  • per line

    Public Sub ParseDoc()
    
        Dim doc As Document
        Set doc = ActiveDocument
        Dim paras As Paragraphs
        Set paras = doc.Paragraphs
        Dim para As Paragraph
        Dim sents As Sentences
        Dim sent As Range
        For Each para In paras
    
            Set sents = para.Range.Sentences
            For Each sent In sents
                Debug.Print sent.Text
            Next
    
        Next
    
    End Sub
    

Object Oriented Database Vs object Relational Database

Hi,

I wonder how Object Oriented data modeling is different from Object Relational data modeling?

Is it something like the pluses of both object oriented and relational data modeling were clubbed to achieve object relational data modeling?

cheers

From stackoverflow
  • this might be helpful comparison of RDM and OOM

  • Object-Relational data modeling supports some object-oriented concepts, while still supporting some relational concepts:

    • Inheritance -- one table can have an IS-A relationship with another table. Likewise custom data types support inheritance.
    • Distinction between a class and an object (instance of a class) that goes beyond simply the distinction between a table and a row.
    • Custom or complex data types.
    • Relational query language.
    • Referential integrity.

    Object-Oriented data modeling is just persistence for objects:

    • Greater support for complex objects.
    • No query language -- you just retrieve individual objects like some giant key/value store.
    • No relational referential integrity -- though you may have one object contain a reference to another object.
    Rik : +1: very good answer

Jquery menu: mouseover/mouseout moseenter/mouseleave craziness

I am trying to craft a simple menu where the first level menu entries are li elements and second level are ul blocks with their own li elements. Nothing really bright. Css contains display:none for all submenus and my (optimistic) idea was simply to show proper ul elements when mouseover is fired on first level entries then to hide them when mouseout is fired on the SUBmenu (the ul element). I have some problem to understand what happened. On Firefox all is nice and the action sequence: enter in the first level menu - enter in submenu - exit from submenu shows that the proper event sequence is triggered: menuOn subMenuOn subMenuOff menuOff. I cannot understand why in IE in the same event sequence subMenuOff is triggered suddenly after subMenuOn: the result is that the submenu immediately disappears. It is like the couple (subMenuOn subMenuOff) was trigegred in the same time disabling submenus. No change using mouseover or mouseenter. Using hover does not change the situation. Have some idea about what happened? This is the code:

   $(document).ready(
     function(){ 
     enableMenu();       
    }
);

var flagOnSubMenu = false;

function enableMenu(){ 
    $('li.menu').bind('mouseenter', menuOn);   
    $('li.menu').bind('mouseleave', menuOff);   
    $('ul.sottomenu').bind ('mouseenter', subMenuOn); 
    $('ul.sottomenu').bind ('mouseleave', subMenuOff); 
}

function menuOn(){ 
    scrivi('menuOn');
    if (flagOnSubMenu){
     scrivi('noAction');
     return;
    }

    var subMenuId;

$('ul.sottomenu').hide();              
        subMenuId = $(this).find("ul").attr('id');
        $('#' + subMenuId ).show();


}

function menuOff(){
    scrivi('menuOff<br>');
    return;
}

function subMenuOn(){
    scrivi('subMenuOn');
    flagOnSubMenu = true;
}

function subMenuOff(){ 
    scrivi('subMenuOff');
    flagOnSubMenu = false;
    $(this).hide();    
}

function scrivi(arg){ 
    $('#debug').html( $('#debug').html() + ' ' + arg );
}
From stackoverflow
  • Some browsers/frameworks bubble the events, some don't.

    i.e. (I'm not sure which way around it goes AFA browsers) One browser will trigger mouseout when the mouse moves from an element to a child element. Another will not but will trigger a mouseover that can be also caught by the parent element.

    Daniel : Not sure about that. I used the hover function too, supposed to solve the problem when moving to a child element. Did not work.
  • I had some crazy issues with mouseover and mouseout events.

    $("#menu>li").hover(
        function(){
            $("#menu *:animated").stop(true,true).hide(); //stop the madness
            $('ul',this).slideDown();
        },
        function(){
            $('ul',this).slideUp("fast");
        }
    );
    

    Stopping the animations was the key for me. Without that, animations would keep firing long after I was finished mousing over my menu.

How do you use grails to connect to wcf HTTPS endpoin w/ Username authentication?

I'm running a WCF service in IIS7 with Username authentication and Message Security.

A client wants but develops using GRAILS. How do they go about connecting and authenticating with the service?

Any information would be greatly appreciated thanks.

From stackoverflow
  • Grails does not handle web services as part of the core framework. Grails is written in Groovy which allows you to use any Java library out there. I would recommend using one of the JAX-WS implementations of web services for Java. Either CXF or Metro should do what you need.

    Essentially you just want to build a client and then call it from the grails application.

Is this an objective-c memory leak?

I know that if you do the following you most certainly have a memory leak:

id foo = [[NSObject alloc] init];
foo = nil;

But, what if you're using self.foo, a property with retain? And your code instead looks like the following:

foo = [[NSObject alloc] init];
self.foo = nil;

Is that still a memory leak since the accessor releases the memory first before setting it to nil?

From stackoverflow
  • self.foo = nil would translate into

    [nil retain]
    [foo release]
    foo = nil
    

    There is no memory leak here.

  • Nope, the second example is not a memory leak. In fact, that's how I deal with retain properties in my dealloc method. It's just a lot cleaner.

    The only thing you have to be careful about is making sure not to write

    self.foo = [[NSObject alloc] init];
    

    or else you'll double-retain the object and end up with a memory leak.

    Marc Charbonneau : Keep in mind using properties in dealloc is usually discouraged in case the accessor method is changed to modify another ivar (which might have already been released). I just use release instead.
    e.James : @Alex: +1 for an excellent warning, but -1 for the suggestion to use self.foo = nil in a dealloc method!
    Jason Coco : @eJames self.foo = nil is the way Apple were recommending doing it in the dealloc method originally and is everywhere in their sample code.
    Alex : I think for run-of-the-mill @synthesize accessors, the property syntax is the way to go. It's good enough for Apple! My thinking is, why spend two lines doing what you could do in one?
    Tom Andersen : Properties in Obj-C 2 look nice, but they add complexity - especially when you can mix and match. I think they should have gone further. Maybe we will will get there in another 15 years with ObjC 3.
  • I don't think so as by doing self.foo = nil you are essentially using the setter and getting the memory management along for free.

  • Properties make it your code look like assignment, but in reality they're the same as traditional accessor methods you might have written yourself prior to Obj-C 2.0. With properties Obj-C is simply generating the accessor methods behind the scenes for you instead using the keywords you specify in the declaration (assuming you use @synthesize and don't write your own accessor methods anyway).

  • No, there is no memory leak. The code in your second example is logically equivalent to

    foo = [[NSObject alloc] init];
    [nil retain];
    [foo release];
    foo = nil;
    

    because the @synthesized setter is logicall equivalent to

    - (void)setFoo:(id)newFoo {
      [newFoo retain];
      [foo release];
      foo = newFoo;
    }
    

    It's worth noting that setting foo directly is probably not something you want to do outside of an init method. If you assign a value to foo directly, you bypass the automatic KVO notification (you would have to wrap your assignment in a willChangeValueForKey:/didChangeValueForKey: pair) and you break any subclass' behavior if it overrides the setFoo: method, expecting all modifications of foo to go through the setter.

    You assign directly to foo in an init method because the setFoo: method or a subclass' overriden setFoo: method may have side-effects or depend on the instance's fully initialized.

    Similarly, you would use [foo release] rather than self.foo = nil; in the -dealloc method for the same reasons.

  • All the answers so far assume that “foo” in the first line of the second example is the instance variable behind the foo property. This is the default behavior.

    If the foo that the first line assigns to is a local variable, then the foo property is irrelevant, and you will leak the object unless you release it later in the method.

    If foo is an instance variable, but the foo property is actually backed by a different instance variable, or no instance variable at all, then (a) you are writing hard-to-maintain code and (b) it may be a leak.

    Finally, echoing the previous answers: If foo is the instance variable backing the foo property, then this is not a leak, since the setFoo: method that you call in the second line will release the object that you put in the foo instance variable in the first line.

LINQ to XML Newbie Question

is there a better way to do this kind of thing:

var filter = new CashFilters();
var element = XElement.Parse(request.OuterXml);

var productId = element.Elements("ProductId").Select(el => el);

if (productId.Count() == 1)
    filter.ProductId = Convert.ToInt32(productId.Single().Value);
From stackoverflow
  • Well, the Select(el => el) isn't doing you any good to start with.

    I suggest you use SingleOrDefault:

    var productId = element.Elements("ProductId").SingleOrDefault();
    if (productId != null)
        filter.ProductId = Convert.ToInt32(productId.Value);
    

    Note that that handles the case where there are no ProductId elements, but will throw an exception if there's more than one. If that's actually a valid case, then your current code (without the redundant Select call) is reasonable.

    EDIT: You could get away from this with:

    var productId = element.Elements("ProductId")
                           .Select(elt => elt.Value)
                           .SingleOrDefault();
    filter.ProductId = Convert.ToInt32(productId ?? filter.ProductId.ToString());
    

    But that's pretty ghastly ;)

    Basically you've got a condition - you only want to set the ProductId if it's specified. An "if" statement is the generally accepted way of conditionally executing code :)

    There are alternatives:

    filter.ProductId = productId == null 
                       ? filter.ProductId 
                       : int.Parse(productId);
    

    If you don't mind filter.ProductId being set to 0 if there's no ID specified, then you can just use:

    filter.ProductId = Convert.ToInt32(element.Elements("ProductId")
                                              .Select(elt => elt.Value)
                                              .SingleOrDefault());
    

    (due to the way that Convert.ToInt32 returns 0 when passed a null argument.)

    AWC : so there's no way to get ride of the null check? great book by the way :)
  • Do you REALLY need to do this in Linq to Xml? The Xml DOM approach seems much more reasonable to me.

    Have you considered the pure Xml approach?

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(request.OuterXml);
    
        var node = doc.SelectSingleNode("//ProductId[1]");
        if (node != null)
            filter.ProductId = Convert.ToInt32(node.InnerText);
    
    Jon Skeet : Personally I prefer the LINQ to XML approach - less scary (uncompiled) string stuff to go wrong. Simply using Elements("ProductId").SingleOrDefault() does the same as the XPath expression, but with less to know IMO.

Programmatically detach SQL Server database to copy mdf file

I have a small SQL Server database that I need to copy on command -- I need to be able to take the mfd and ldf files at any given moment, copy them, zip them, and make them available to an end user.

Right now this is possible by manually:

1) Logging onto the SQL server via Remote Desktop

2) Detaching the database via SQL Management Studio. I have to fiddle around with a combination of setting the database to single_user and/or restarting the service so I can get it to detach since the app server is normally logged into it.

3) While detached I go through the file system and copy the mdf and ldf files.

4) I re-attach the database via SQL Management Studio

5) I zip the copied files, and I move them to an FTP server so the people who need them can get them.

It's a horrible, inefficient process. It's not just a matter of needing the schema, but rather a need for people to work with snapshots of real, production data on their own local machines for the purpose of destructive experimentation. Luckily the zipped database is very small -- maybe 30 megs with the log.

So ideally, I'd like to create a page in the ASP .NET web application that has a button the user can press to initiate the packaging of the current database into a zip file, and then I'd just provide the link to the file download.

From stackoverflow
  • Easy - check into the "SQL management objects" SMO that come with SQL Server - nice C# / VB.NET classes and methods to do all of this.

    See: SMO - manage your SQL Server!

    or:

    SQL Server 2005 Database Backup and Restore using C# and .NET 2.0

    Marc

  • Why not make a ordinary backup (easy to do with sqlcommand) and add a feature for the users to easy restore that backupfile with a click on a button?

    • You can backup the database with sql-commands
    • You can shell out and zip the backupfile with sql-commands
    • You can also shell out and ftp the backupfile automagically to an webserver if you want.

    What are the end users using to consume your db? A winform-program? Then it easy done to do everything with a button click for the user.

    Here are some example code for that:

    Declare @CustomerID int
    declare @FileName nvarchar(40)
    declare @ZipFileName nvarchar(40)
    declare @ZipComand nvarchar(255)
    
    
    set @CustomerID=20 --Get from database instead in real life application
    SET @FileName='c:\backups\myback'+ cast(@customerID as nvarchar(10))+'.bak'
    SET @ZipFileName='c:\backups\myback'+ cast(@customerID as nvarchar(10))+'.zip'
    
    --Backup database northwind
    backup database northwind to DISK=@FileName
    
    --Zip the file, I got a commanddriven zip.exe from the net somewhere.
    set @ZipComand= 'zip.exe -r '+@ZipFileName+' '+@FileName
    EXEC xp_cmdshell @zipcomand,NO_output
    
    --Execute the batfile that ftp:s the file to the server
    exec xp_cmdshell 'c:\movetoftp.bat',no_output
    
    --Done!
    

    You have to have a movetoftp.bat that contains this (change ftp-server to your):
    ftp -s:ftpcommands.txt ftp.myftp.net

    And you have to have a ftpcommands.txt that contains this (You can have this file created dnamically with just the right zip-file by sqlcommands too, but I let you do that yourself):

    ftpusername
    ftppassword
    binary
    prompt n
    mput c:\backups\*.zip
    quit

  • Look at the dialogues you use in SQL Management Studio, near the top of each is a button which will generate a scrip to perform the action. This is a quick way to discover how to do this in SQL which can be executed from a database connection.

    E.g. to detach database db1:

    EXEC master.dbo.sp_detach_db @dbname = N'db1'
    
    Stefan Valianu : Pointing out the existence of the script button was extremely useful. +1
  • Personally I'd generate backups of the database and zip those and send them to the users. Perhaps you could write a small script to restore.

    Reason being detaching the database makes it unavailable for others.

  • I'd use SQL Dumper console version and compress the sql dump.

    IMHO it's always better to have a plain text copy instead of a binary file. If something goes wrong, at least you can rewrite your data by hand, because you can read it.

Can you resize a C++ array after initialization?

I'm learning to program, and C++ is my first language. Don't bother using pointers to show me - I don't understand them yet, and won't bother until I have more free time to dedicate to this.

    int mergeSort()
{
    const int n = 9;
    int originalarray[n] = {1, 3, 5, 7, 9, 2, 4, 6, 8};


    const int halfelements = (sizeof(originalarray) / sizeof(int)) / 2;
    int farray[halfelements];
    int sarray[halfelements];

    for (int i = 0; i < halfelements; i++) {
        farray[i] = originalarray[i];
    }

    for (int i = halfelements, x = 0; i < (halfelements * 2); i++, x++) {
        sarray[x] = originalarray[i];
    }

I was assigned (I'm not taking classes - just learning with a few friends helping me out) a merge sort algorithm, with the algorithm explained but not the implementation. I want to rewrite this so it will work for both odd and even integers. I tried adding this code:

if ((n % 2) != 0) int farray[halfelements + 1];

So that I could use the same integer to iterate over both subsequent arrays. A sizeof(farray) is showing to be 16 bytes, or 4 integers. So it isn't resizing. What I want to know - is it possible to resize arrays after they initialized?

Edit: How would I implement a vector? I don't understand how to use iterators in a loop to iterate over and copy the values.

From stackoverflow
  • C++ arrays are fixed in size.

    If you need a "resizable array", you'll want to use std::vector instead of an array.

    Hooked : OK, thanks. I've figured out how you would implement std::vector's into this algorithm. Although I wish I hadn't spent two hours debugging my code, just to figure out my function header "int mergeSort(std::vector, int)" was missing an "" =/
  • If you want to resize an array, you probably want to use a vector, which can be resized automatically.

  • My advice is even stronger: use std::vector<> (et. al.) unless you have a very good reason to use a C-style array. Since you're learning C++, I doubt you have such a reason: use std::vector<>.

    Richard : Given a vector is guarenteed to use contiguous storage, even when passing to a method taking pointer you can use a vector. Only when passing a reference/pointer to a pointer for a method to size the data are you stuck with using raw memory.
  • You can use the [] operator with a vector the same way you would in an array. You could implement this with a vector something like this (if you wanted to use more vector methods):

    #include <vector>
    
    const int halfelements = originalarray.size()/2; //use size to get size
    vector <int> farray(halfelements);
    vector <int> farray(halfelements);
    
    for (int i = 0; i < halfelements; i++) {
        farray.push_back(originalarray[i]); //adds element at i to the end of vector
    }
    
    for (int i = halfelements, x = 0; i < (halfelements * 2); i++, x++) {
        sarray.push_back(originalarray[i]);
    }
    

    You can also use .at(index) to add bounds checking to the vector access.

    anon : please don't use the "pre" HTML tag for code - instead, select the code with your mouse and type ctrl-K or click on the code icon
    jmucchiello : He should be using the vector(iter, iter) constructors. vector farray(originalarray.begin(), &originalarray[half]), sarray(&originalarray[half], originalarray.end()); It eliminates the copy afterward. But that's probably confusing.
  • If you want to know why your first idea compiled but didn't seem to work:

    When you omit braces in an if-statement:

    if ((n % 2) != 0) int farray[halfelements + 1];
    

    it's just the same as if you'd used them:

    if ((n % 2) != 0) {
      int farray[halfelements + 1];
    }
    

    So it is making an 'farray' of the correct size -- and then it immediately goes out of scope and is gone, and you're left with only the original one.

  • I would also recommend std::vector. However if you are stuck with an array you can always malloc the memory and then realloc if you need to make the array larger.

    Do a search here on SO, there is information about malloc and realloc.

Why can't my Perl script load a module when run by cron?

I have a bunch of Perl scripts that all run fine, yet need to have use Plibdata; up top.

I set up a cron job that runs (I get the confirmation email from root) and it spits back the following error message:


Can't locate Plibdata.pm in @INC (@INC contains: /install/lib /opt/perl58/lib/5.8.8/IA64.ARCHREV_0-thread-multi /opt/perl58/lib/5.8.8 /opt/perl58/lib/site_perl/5.8.8/IA64.ARCHREV_0-thread-multi /opt/perl58/lib/site_perl/5.8.8 /opt/perl58/lib/site_perl .) at ./x line 5.

BEGIN failed--compilation aborted at ./x line 5.


Line 5 is... you guessed it.... use Plibdata;

I am also attempting to set the environment as such..
use lib "$ENV{CARSPATH}/install/lib";
so maybe if I found the location of this plibdata, I could explicitly direct it that way?

My cron commands will be executed using /usr/bin/sh says crontabs....

Any suggestions?

This script works from the command line.

From stackoverflow
  • You don't say what Plibdata is. You also don't state if this works at your command prompt. I assume that it does.

    Try this:

    perl -MPlibdata -e 1
    

    Assuming that doesn't spit the same error, try this:

    perl -MPlibdata -le 'print $INC{"Plibdata.pm"}'
    

    That will tell you where. (It's probably in your PERL5LIB env var if this works.) Then you can just add the appropriate "use lib" to the directory Plibdata.pm is in.

    Also, be sure you're using the same perl in both locations - command line ("which perl") and in the cron job (try "BEGIN { print $^X }" at the top of your script).

    CheeseConQueso : those both gave me back the same error message as mentioned above
    Tanktalus : Ok, so what does $CARSPATH contain? "echo $CARSPATH" at the command line. If that shows nothing, then you'll need to talk to your fellow developers about where it really is.
    Tanktalus : And is there a /opt/carsi/install/lib/Plibdata.pm ? You'll either have to use lib "/opt/carsi/install/lib";, or use lib "$ENV{CARSPATH}/install/lib"; and find a way to set CARSPATH in your crontab or something (that becomes a new question).
    CheeseConQueso : yeah im using that exact syntax.. the 2nd one... ill try the 1st version (essentially the same, but more explicit) thanks for all the help
    CheeseConQueso : oh and yes /opt/carsi/install/lib/Plibdata.pm exists
  • Cron uses a different user env than your env when logged in. Are you able to run the script from the command line? If so, just set your env variables inside the cron above your current commands.

    Dana the Sane : The question does seem to state that they run from the commandline. I'm pretty sure you're right about environment variables not being set.
    CheeseConQueso : how would i go about doing that? inside the cron.txt?
  • cron does not setup an environment for you when it runs your code, so the environment variable $CARSPATH does not exist. I suggest only running shell scripts from cron, setting the environment inside of the shell script and then running the program you really wanted to run.

    example wrapper script:

    #!/bin/bash
    
    source ~username/.bash_profile
    cd ~username
    ./script.pl
    

    If you are using ksh or sh you may need to say

    #!/bin/sh
    
    . ~username/.profile
    cd ~username
    ./script.pl
    

    Remember to replace username with your username on the system. Also, if the script is not in your home directory you will want to execute it with the path to it, not ./.

    You say source, or period space, to load a given shell script in the current shell. You load it in the current shell so that any environment settings stay with the current shell.

    ~/.bash_profile, ~/.bashrc, ~/.profile, /etc/profile, etc. are all files that commonly hold your environment setup. Which one you are using depends heavily on your OS and who set it up.

    CheeseConQueso : how can i set the environment inside a shell script? #!/bin/ksh ?
    CheeseConQueso : it wont run from the command line..... interpreter "/bin/bash" not found file link resolves to "/usr/bin/bash" .......... can it be done with #!/bin/ksh ?
    CheeseConQueso : i tried a couple different combinations.... it seems that i need bash instead of ksh for the source ~CheeseConQueso/.bash_profile to work... ksh ignores it, spits an error, then runs the script normally.. and i tried .ksh_profile - no luck there either
    Chas. Owens : Yes, but change "source" to "." and ".bash_profile" to ".profile". This also assumes CheeseConQueso (with that casing) is your username on that system.
    Chas. Owens : It also assumes that the script is in your home directory, you may need to change the path.
    brian d foy : Rather than relying on the .bash_profile to set up your environment, make any script (not just Perl), handle the things it needs to setup. Either that, or make a special profile for cron, or set the environment variables, like PERL5LIB, in your crontab.
    CheeseConQueso : @chas yeah i changed the CCQ to my username and the script is in my home dir... ill try it out.. thanks
    CheeseConQueso : ok now i hit another wall... when i log in, i hit a prompt to select a database or quit... so when i ran it from the command line, it brought me to that prompt. then i chose my db and it ran the script fine. set up the cron but i suppose it never got past the prompt because nothing happened
    Chas. Owens : You have a prompt in your .profile? That is not normal. Well, you are going to need to create a separate file that sets up the environment you want the shell to have and source it instead of your .profile.
  • Clearly, Plibdata.pm is not installed in the default module paths on your system: /install/lib /opt/perl58/lib/5.8.8/IA64.ARCHREV_0-thread-multi /opt/perl58/lib/5.8.8 /opt/perl58/lib/site_perl/5.8.8/IA64.ARCHREV_0-thread-multi /opt/perl58/lib/site_perl/5.8.8 /opt/perl58/lib/site_perl

    You have three choices:

    1. Install Plibdata.pm in a known perl system path (site_perl is the classic option).

    2. Make the PERL5LIB shell environment (or the equivalent command line -I option for perl) include the installation path of the module.

    3. Use "use lib" in your script. Remember that the "use lib" action is done at compile time, so your variable in the path may not be initialised. Try using the variable in a BEGIN block like this:

      my $env;

      BEGIN { $env = $ENV{CARSPATH}; }

      use lib "$env/install/lib";

    Chas. Owens : Only number 1 will work. He/She is running the code under cron and therefor does not have an environment
    CheeseConQueso : I think I'm already doing that..... use lib "$ENV{CARSPATH}/install/lib"; is also up in the use block
    : CheeseConQueso: THe important part is the BEGIN block. This executes at compile time and not at run time. Both steps occur when you run perl, but in a classic strict order: compile->run. nxadm
    CheeseConQueso : ahhh ok thanks for the heads up... thats good to know
  • Although its not an 'answer', I resolved this issue by using DBI instead of the Plibdata.

    Which is kind of milky because now I will have to change a couple scripts around... ahhhhh I wish there was something I could do to make the Plibdata work

    I'm still going to try Chas. Owens answer to see if that works


    didn't work for me... "interpreter "/bin/bash" not found"
    maybe it would work with people who have that interpreter



    * * * * * CARSPATH=/opt/carsi ./x
    

    works

  • Running your program from a wrapper script as others have suggested is probably my preferred method, but there may be a few other solutions:

    If you're using a modern cron you may be able to do something like this in your crontab entry:

    * * * * * CARSPATH=/opt/carsi x
    

    replacing the asterisks with the appropriate schedule designators.

    This will set CARSPATH for the x process and allow the use lib statement that passes the environment variable to work.

    You can also, depending on your shell and cron implementation, store your environment setup in a file and do something like:

    * * * * * source specialenv.sh && x
    

    Where specialenv.sh contains lines like (for bash)

    export CARSPATH=/opt/carsi
    

    You may also be able to set environment variables directly in the crontab, should you choose to do so.

    CheeseConQueso : * * * * * CARSPATH=/opt/carsi x FOR THE WIN!!

Do templated classes inherit the members of the classes passed to them? (Specificly std::vector)

Hi,

I have a question regarding vectors:

If I have a std::vector<MyClass> will this vector "inherit" the MyClass member functions or not? If not, then would be the best way to handle individually the MyClass members inside a loop? Would I have to create a new class object on each iteration and assign the current vector iterator to it?

class MyClass
{
    public:
        void setMembers(std::string &string, int &num)
        {
            mystring = string;
            number = num;
        }
        string printString() { return mystring; }
        int printNumber() { return number; }

    private:
        std::string mystring;
        int number;
};

    MyClass test;
    std::vector<MyClass> vector;

    std::string string = "Test 1";
    int a = 3;

    test.setMembers(string,a);
    vector.push_back(test);

    for(unsigned int i = 0; i<vector.size(); i++) {
        cout << "Vector #" <<  << endl;
        // does vector inherit member functions here?
        cout << "mystring is: " << vector.printString()<< endl;
        cout << "number is  : " << vector.printNumber() << endl;
    }

Thanks a lot in advance for your help.

From stackoverflow
  • No it does not. You need to access each member of the collection:

    cout << "Vector #" <<  << endl;
    for( unsigned int i = 0; i <vector.size(); i++) {
        cout << "mystring at " << i << " is "  << vector[i].printString()<< endl;
        cout << "number at " << i << " is " << vector[i].printNumber() << endl;
    }
    
  • No. Vector is a container around objects of your class type. You need to index your vector with operator[] or the at() member functions to access your class objects. Then you can call those functions on your objects.

    E.g.

    v[i].printString();

    or

    v.at(i).pringString();

  • No, the instance std::vector doesn't inherit your member variables. However the objects in the vector do have those member which you can access via operator[].

    for (size_t i = 0; i < vector.size(); i++) {
        cout << "Vector #" << i << endl;
        cout << "mystring is: " << vector[i].printString() << endl;
        cout << "number is  : " << vector[i].printNumber() << endl;
    }
    

    Notice we say vector[i] now, which returns a value of type MyClass which does have the member functions printString() and printNumber().

    You should go re-read the chapter on inheritance.

  • No. A vector is like an array; it's a collection of what it holds, not a subclass of what it holds.

  • No, the vector does not "inherit" members of the class. If you want to do something for each element of the vector, use an iterator:

    for(vector<MyClass>::iterator i=vector.begin();i!=vector.end();i++) {
        cout << "mystring is: " << i->printString() << endl;
        cout << "number is  : " << i->printNumber() << endl;
    }
    
  • The vector inherits nothing from its class, but the members are members of the class.

    Suppose you had std::vector<MyClass> v;, and actually got some members in (it looks like you're fine with .push_back()).

    Now, you can call the MyClass functions from something like:

    for (int i = 0; i < v.length(); ++v)
       v[i].printString();
    

    or

    for (std::vector<MyClass>::const_iterator i = v.begin(); i != v.end(); ++i)
       i->PrintString();
    
  • Consider it from the "Is a / has a" point of view The vector isn't a "MyClass" it has a "MyClass" (actually it has 0 or more MyClass), but the important thing is that is isn't a MyClass, it just stores them

    Each object you put into the vector stays there, you can refernce each obect by position (as if it were an array of MyClass objects)

    for(unsigned int i = 0; i<vector.size(); i++) {
        cout << "Vector #" <<  << endl;
        // does vector inherit member functions here?
        cout << "mystring is: " << vector[i].printString()<< endl;
        cout << "number is  : " << vector[i].printNumber() << endl;
    }
    

    however the convention is to use iterators, which act "like" pointers to the stored objects e.g.

    for(std::vector<MyClass>::iterator i = vector.begin(); i != vector.end(); ++i) {
        cout << "Vector #" <<  << endl;
        // does vector inherit member functions here?
        cout << "mystring is: " << i->printString()<< endl;
        cout << "number is  : " << i->printNumber() << endl;
    }
    

    Hope this helps to clarify things.

    Kevin : You need to fix your example to be "std::vector::iterator" type for i
    Binary Worrier : Thanks Kev, it's my own fault for typing code directly into an answer :)
  • Thanks for all the answers! It turned out to be easier than I thought and it makes a lot of sense now.

    I shouldn't have used the word inherited since it means a totally different thing.

    Anyways, all of your answers helped a lot. Thank you very much!

  • The first part of your question has already been answered by others. No form of inheritance takes place. The vector behaves as a vector, and nothing else.

    There are two ways to manipulate arrays. The first (obvious) one is through a for loop, like you said:

    for(size_t i = 0; i<vector.size(); i++) { // technically, you should use size_t here, since that is the type returned by vector.size()
        cout << "Element #" <<  << endl; // We're iterating through the elements contained in the vector, so printing "Vector #" doesn't make sense. There is only one vector
        cout << "mystring is: " << vector[i].printString()<< endl; // [i] to access the i'th element contained in the vector
        cout << "number is  : " << vector[i].printNumber() << endl;
    }
    

    The other approach is to use the algorithms defined in the standard library. As an introduction to those, I'm going to split it up into a few steps. First, every container also defines an iterator type. Iterators are conceptually like pointers that point to a location in the container. So instead of vector[i].printString(), you can call printString() on the element point to by any given iterator. (assuming an iterator called iter, the syntax would be iter->printString())

    The reason for this is that it allows a common and generic way to traverse containers. Because lists, vectors, deques and all other container types all provide iterators, and these iterators use the same syntax, your code can take a pair of iterators, denoting the beginning and the end of the range of elements you want to process, and then the same code will work regardless of the underlying container type.

    So first, let's use a loop to run through the container again, but this time using iterators:

    forstd::vector<MyClass> current = vector.begin(); current != vector.end(); ++current) {
        cout << "mystring is: " << current->printString() << endl;
        cout << "number is  : " << current->printNumber() << endl;
    }
    

    Not a huge improvement so far, although it does eliminate the i index variable, which often isn't necessary, except as a loop counter. The begin/end) functions return an iterator pointing to the first element in the container, and another pointing one past the end of the iterator. So as we move the first iterator forward, we know we've reached the end when it equals the end iterator. In this way, two iterators can represent any range of elements.

    Now that we have iterators though, we can use a lot of other tricks. The C++ standard library comes with a number of algorithms for processing sequences of elements. They're located in the <algorithm> header.

    A simple one to get us started is std::for_each, which is almost a drop-in replacement for a for loop. It is simply a function which takes two iterators, denoting the range of elements it should process, and an action it should perform on each. So to call it, we need to define such an action:

    void Print(const MyClass& obj) {
        cout << "mystring is: " << obj.printString() << endl;
        cout << "number is  : " << obj.printNumber() << endl;
    }
    

    That's all. A function which takes the element type as a parameter, and does whatever needs to be done. Now we can call for_each:

    std::for_each(vector.begin(), vector.end(), Print);
    

    If you need to do this often, it saves a lot of typing. The Print function only has to be defined once, and then every for loop can be replaced with such a one-liner.

    Another nice trick with iterators is that they don't have to represent the entire range. We could skip the first five elements:

    std::for_each(vector.begin() + 5, vector.end(), Print);
    

    or take only the first three elements:

    std::for_each(vector.begin(), vector.begin()+3, Print);
    

    or any other manipulation you can think of. There are also algorithms such as copy (copy from one iterator range to another):

    std::copy(vector.begin(), vector.end(), dest.begin());
    

    And dest may be any type of iterator as well, it doesn't have to be a vector iterator just because the source is. In fact we could even copy directly to std::cout if you wanted to print out the contents directly (unfortunately, since MyClass doesn't define the operator <<, that would result in an error.)

    to work around this little problem with std::cout, we could use std::transform, which applies some transformation to each object, and then places the result into an output sequence. Since we can't directly print out a MyClass objec, we could just transform it to a string, which can be printed out:

    std::string ToString(const MyClass& obj) {
      return std::string("mystring is: " + obj.printString() + "\nnumber is  :" << obj.printNumber() + "\n";
    }
    

    Again, fairly simple code. We simply create a function which takes a MyClass object, and builds a string with the desired output. So let's copy this directly to std::cout:

    std::transform(vector.begin(), vector.end(), std::ostream_iterator(std::cout), ToString);
    

    std::ostream_iterator creates a special output stream iterator out of std::cout to allow it to function as an iterator. And once again, the actual "do this on everything in the vector" code became a single line. The actual action to perform is defined once, elsewhere, so it doesn't have to clutter up the code.

    So while a for loop is the immediately obvious way to process sequences of elements in a container, iterators are often a better solution in the long run. They offer a lot more flexibility, and even simplifies your code quite a bit.

    I won't blame you if you prefer to stick with for loops for now, as they're a bit easier to grok. I simply wanted to show you that they're not the "ultimate" answer in C++.

    nmuntz : Thank you very much for your very thoroughly explanation, this will help me a lot actually! I really liked the for_each() solution that you gave. I really appreciate all the extra effort you took here to explain to me this. Thanks a lot!!!
    jalf : No problem. It's always a pleasure to help people discover that there's actually a fairly elegant language hidden inside C++. It's well hidden, but knowing it's there can save you a lot of headaches ;)
    Binary Worrier : Dude +1 for a truly EPIC answer!
  • No, std::vector<MyClass> does not inherit the members of MyClass but you can use STL's and boost's facilities to perfrom operations on the vector without explicitly coding an iteration for each operation you need.
    Here's some sample code:

    #include <vector>
    #include <algorithm>
    #include <boost/bind.hpp>
    
    struct Bla
    {
        Bla(int i = 0) : m_i(i) {}
    
        void print() { printf("%d ", m_i); }
        void printAdd(int a) { printf("%d ", m_i +  a); }
    
        Bla add(int a) { return Bla(m_i + a); }
        int geti() { return m_i; }
    
        int m_i;
    };
    
    void printInt(int i)
    {
        printf("%d ", i);
    }
    
    int main(int argc, char *argv[])
    {
        std::vector<Bla> bla;
        bla.push_back(Bla(1));
        bla.push_back(Bla(2));
    
        // print the elements in the vector
        std::for_each(bla.begin(), bla.end(), boost::mem_fn(&Bla::print));
        printf("\n");
        // a complex operation on the vector requiring an additional argument for the call
        std::for_each(bla.begin(), bla.end(), boost::bind(&Bla::printAdd, _1, 10));
        printf("\n");
    
        // extract a single member from the vector into a second vector
        std::vector<int> result;
        result.resize(bla.size());
        std::transform(bla.begin(), bla.end(), result.begin(), boost::bind(&Bla::geti, _1));
        // print the result
        std::for_each(result.begin(), result.end(), &printInt);
        printf("\n");
    
        // transform the vector into a different vector using a complex function that requires an argument.
        std::vector<Bla> result2;
        result2.resize(bla.size());
        std::transform(bla.begin(), bla.end(), result2.begin(), boost::bind(&Bla::add, _1, 10));
        std::for_each(result2.begin(), result2.end(), boost::mem_fn(&Bla::print));
        printf("\n");
    
        return 0;
    }