Like Tree11Likes

Create vector of floats in a for-loop

This is a discussion on Create vector of floats in a for-loop within the C++ Programming forums, part of the General Programming Boards category; I would like to produce five vectors via for-loop Code: for(int i =0; i<5; i++) { vector<float> someVector_%d ; } ...

  1. #1
    Registered User
    Join Date
    Dec 2012
    Posts
    12

    Create vector of floats in a for-loop

    I would like to produce five vectors via for-loop
    Code:
    for(int i =0; i<5; i++) {
      vector<float> someVector_%d ;
    }
    so that i have

    Code:
     vector<float> someVector_0
    vector<float> someVector_1
    vector<float> someVector_2
    vector<float> someVector_3
    vector<float> someVector_4

  2. #2
    Registered User manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    Kolkata@India
    Posts
    2,498
    What for ?
    Your someVector_%d objects won't be accessible outside the loop because they have local scope.
    Whatever you want to do with these, you can do with an array or vector of vector<float> s.
    Manasij Mukherjee | gcc-4.8.2 @Arch Linux
    Slow and Steady wins the race... if and only if :
    1.None of the other participants are fast and steady.
    2.The fast and unsteady suddenly falls asleep while running !



  3. #3
    Registered User
    Join Date
    Dec 2012
    Posts
    12
    my only problem is to concatenate someVector_ with the integer in the for-loop, so that for instance I produce someVector_0

  4. #4
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    682
    You'd better tell us what you really want to achieve. You cannot dynamically change identifier's name and what you are trying to do may come from dynamically typed language background.
    I never put signature, but I decided to make an exception.

  5. #5
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,756
    You could use an array of vectors:
    std::array<std::vector<float>>
    But still, telling us what you want to achieve may be the best thing to do in the end.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,308
    You're asking the wrong question. Any time you want to have a bunch of different variables with an increasing number on the end of each subsequent one, then you should be using an array. I.e.:
    Code:
    vector<float> someVector[5];
    Then instead of referring to e.g. someVector_2, you refer to someVector[2] in your code; although you'll most often find that you don't need to refer to specific array items, as you tend to use a loop to to anything with them.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  7. #7
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,756
    Please don't teach newbies bad practices.
    Anytime an array is to be used, they should be using C++-style arrays (ie std::array), and not C arrays.
    Furthermore, if possible, they should be using the .at function and not the index operator to avoid having to think about out of bounds access.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    Registered User
    Join Date
    Jun 2005
    Posts
    6,420
    Quote Originally Posted by Elysia View Post
    Anytime an array is to be used, they should be using C++-style arrays (ie std::array), and not C arrays.
    Furthermore, if possible, they should be using the .at function and not the index operator to avoid having to think about out of bounds access.
    The approach shown by iMalc is an alternative, not bad practice. Unlike the approach you recommend, it is also a practice guaranteed to be supported by all compilers/libraries.

    std::array was only formally introduced into the standard in 2011, so is unlikely to be supported by compilers/libraries more than a year old, and it is not certain when it will be supported by more recent compilers. On the other hand, the approach suggested by iMalc has been supported by the first C++ standard in 1998.

    Introduction of a new feature in a standard does not automatically render preceding features to be "bad practice". Your technique of nagging people who provide help to newbies is not the way to encourage the newer practices.


    Providing an incomplete/incorrect example, as you did, will not encourage newer practices either. std::array has two template parameters, one of which is the size (which cannot subsequently be changed).
    jimblumberg and iMalc like this.
    Right 98% of the time, and don't care about the other 3%.

  9. #9
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,756
    Quote Originally Posted by grumpy View Post
    The approach shown by iMalc is an alternative, not bad practice. Unlike the approach you recommend, it is also a practice guaranteed to be supported by all compilers/libraries.
    I consider it bad practice since the standard gave us a better way to do it, which means we should be using the better approach, if possible.

    std::array was only formally introduced into the standard in 2011, so is unlikely to be supported by compilers/libraries more than a year old, and it is not certain when it will be supported by more recent compilers. On the other hand, the approach suggested by iMalc has been supported by the first C++ standard in 1998.
    std::array was introduced in TR1, which was finalized 2007.

    Introduction of a new feature in a standard does not automatically render preceding features to be "bad practice". Your technique of nagging people who provide help to newbies is not the way to encourage the newer practices.
    Of course it is bad practice to use unsafe features, libraries and code when you have the option to use newer, safer technology!
    Yes, I understand that you might not always be able to do so, but in this case, I think it is pretty clear that it should definitely be possible.
    I am partly to blame for nagging and for nagging people to use C++11 features. But I also think iMalc is partly to blame here, too. Sure, you can use C arrays, but iMalc failed to specify the disadvantage of doing so and completely failed to mention std::array.
    We cannot keep pushing older features onto newbies! C++ is a wonderful language, but it can be disastrous if used wrong, and that is partly why it has been viewed so negatively, I would think. We should teach newbies that C++ is not a low-level, ancient, relic language that you should only use for absolute maximum performance and embedded systems, but for other purposes too!
    rray
    Providing an incomplete/incorrect example, as you did, will not encourage newer practices either. std::array has two template parameters, one of which is the size (which cannot subsequently be changed).
    That was a typo.
    In retrospect, I should have written

    std::array<std::vector<float>, 5> array;

    // Use it like this:
    array.at(N); // Where N is a number between 0 and 4.

    And obviously the size cannot be changed later on - but that's no different from a C array. It's static.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Registered User
    Join Date
    Jun 2005
    Posts
    6,420
    Quote Originally Posted by Elysia View Post
    std::array was introduced in TR1, which was finalized 2007.
    TR1 was a set of proposed extensions to the standard. Although it was a standard, it was never formally a C++ standard. Features in it became part of the C++ standard in C++-11.

    Quote Originally Posted by Elysia View Post
    Of course it is bad practice to use unsafe features, libraries and code when you have the option to use newer, safer technology!
    Life is not that simple in the real world. Good practice can involve disciplined and effective use of available features, avoiding misuse, etc. I've seen enough "bad practice" that involves misuse of ostensibly safe features coupled with over-confidence since "it is safe, isn't it, so I can do what I like without checking". Including, in some cases, with misuse of std::array.

    There is also the inconvenient fact that std::array is just a wrapper that provides an alternative interface for a normal array anyway. It is designed as a means of convenience, not a safety mechanism. It can be used in safe ways, or unsafe ways.

    Quote Originally Posted by Elysia View Post
    I am partly to blame for nagging and for nagging people to use C++11 features.
    My point exactly. Yes, C++-11 features are useful. Yes, they can be safer. They are not, however, a safety net. And they can still be misused.

    Unfortunately, the intelligence and skill of the C++ standards committee - although considerable - is bounded and finite. In contrast, the propensity of programmers to misuse language features has no known upper bound.

    Quote Originally Posted by Elysia View Post
    But I also think iMalc is partly to blame here, too. Sure, you can use C arrays, but iMalc failed to specify the disadvantage of doing so and completely failed to mention std::array.
    I disagree. His post was immediately after your post that mentioned std::array. By your logic, you had the obligation to mention C-style arrays as well, so his post should not have been necessary. Such an argument cuts both ways.

    However, in forums, we don't aim for completeness - because we can't - unless there is a particular reason to. We provide options and discussion, not definitive or complete descriptions of everything.

    Quote Originally Posted by Elysia View Post
    We cannot keep pushing older features onto newbies! C++ is a wonderful language, but it can be disastrous if used wrong, and that is partly why it has been viewed so negatively, I would think.
    In my experience, the largest source of negative comments about C++ comes from advocates of other languages, which do things differently than C++. Some of those languages are still around and in common usage but, in most cases, C++ has grown while those languages have fallen away.

    Describing features of language that newbies will encounter regularly when they look at code written by others - even code that is relatively recent - is hardly "pushing older features on newbies". Practically, a lot of newbies in industry cut their teeth by maintaining code written by others, not by writing their own brand-new code.

    There are also plenty of legitimate criticisms of C++, including some written by the greats in the C++ world. Those have contributed to improvement of C++ over time.

    Quote Originally Posted by Elysia View Post
    We should teach newbies that C++ is not a low-level, ancient, relic language that you should only use for absolute maximum performance and embedded systems, but for other purposes too!
    We should teach C++ as a multi-paradigm language. Not a particular paradigm based solely on using the latest features, which is what I consider you are advocating. Such an approach is essentially locking developers into a ivory tower, since very few real-world developers can afford to limit their attention to the latest new feature sets.

    I'm not alone in suggesting that. Recent teaching materials from people like Stroustrup do it too - although it is easier to take a staged approach to teaching when you can control the materials. A staged approach is not really practical in a forum with multiple independent contributors, but your approach of advocating the "latest, greatest, and allegedly safest while nagging those who provide alternatives" is not the answer to that problem.
    Right 98% of the time, and don't care about the other 3%.

  11. #11
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,738
    You can nag Elysia as much as you want but he continues to fail to mention when he is using C++11 features (secretly) to this day, despite the fact that C++11 is not the default implementation any compiler I know uses. A practice I consider most harmful because people essentially end up not knowing what they're using. It will generate compiler errors that should be unnecessary, but the fact that a switch needs to be flipped is never mentioned by him. He leaves that responsibility to other people.
    Last edited by whiteflags; 12-24-2012 at 06:11 PM.
    grumpy and jimblumberg like this.

  12. #12
    Registered User
    Join Date
    Dec 2012
    Posts
    12
    ok, consider the picture
    Code:
     float x = 50.;
     float y;
    for(int ivector = 0; ivector<20; ivector++) {
       vector<float> someVector_%d //my problem lies here
       /* here i want to generate 20 vectors
            vector<float> someVector_0
            vector<float> someVector_1
            vector<float> someVector_2
    
                  up to 
             vector<float> someVector_19
       */
    
        for(int i = 0; i<1000; i++) {
            y = x*i*ivector;
           someVector_%d.push_back(y); //so this is what i want to do. %d is the current ivector in the loop . What I want to achieve is : concatenate someVector_ and %d
        }
    
    }
    I hope it makes the aim clearer

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,883
    Quote Originally Posted by fclopez
    Code:
       vector<float> someVector_%d //my problem lies here
       /* here i want to generate 20 vectors
            vector<float> someVector_0
            vector<float> someVector_1
            vector<float> someVector_2
    The point that has been made to you earlier in this thread is that instead of trying to do that (some kind of "variable variables" to borrow the term from PHP), create a container of vector<float> objects. This can be a vector of vector<float> objects, or if you are really fixed at 20 such vectors, then a fixed size array (whether a built-in array or std::array) will do.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  14. #14
    Registered User
    Join Date
    Jun 2005
    Posts
    6,420
    Quote Originally Posted by fclopez View Post
    I hope it makes the aim clearer
    It is just a restatement of the original question. There is no way in C++ to concatenate an integral value computed in a loop to a variable name, in order to create another variable name. Restating the problem does not make it solvable if it is not already solvable. C++ is not PHP, and cannot be used as if it is.

    What you need to do is create an array (or a container) of vectors. There are various options.
    Code:
    std::vector<std::vector<float> > someVector(20);     // creates a vector containing 20 vectors.
    for(int ivector = 0; ivector<20; ivector++)
    {
        for(int i = 0; i<1000; i++)
        {
            y = x*i*ivector;
           someVector[ivector].push_back(y); //  this is a functional equivalent of what you have described as someVector_%d.push_back(y)
    
              //   or, alternatively,   someVector.at(ivector).push_back(y);
        }
    }
    or (using a naked array, like described by iMalc)
    Code:
    std::vector<float> someVector[20];     // creates a array containing 20 vectors.
    for(int ivector = 0; ivector<20; ivector++)
    {
        for(int i = 0; i<1000; i++)
        {
            y = x*i*ivector;
           someVector[ivector].push_back(y); //  this is a functional equivalent of what you have described as someVector_%d.push_back(y)
        }
    }
    or using the std::array approach advocated as the bees knees by Elysia (although it relies on you having access to C++-11 compliant compiler)
    Code:
    std::array<std::vector<float>, 20> someVector;     // creates a array containing 20 vectors.
    for(int ivector = 0; ivector<20; ivector++)
    {
        for(int i = 0; i<1000; i++)
        {
            y = x*i*ivector;
           someVector[ivector].push_back(y); //  this is a functional equivalent of what you have described as someVector_%d.push_back(y)
              //   or, alternatively,   someVector.at(ivector).push_back(y);
        }
    }
    There are differences between these, and each technique has advantages and disadvantages.

    The first and second are supported by all versions of C++ (i.e. by the standard since 1998). The third method is not.

    The first approach allows the number of vectors to be changed later, the second and third approaches do not.

    The first and third approaches are considered "safer" by some if the someVector.at(ivector) is used instead of someVector[ivector] (assuming you know how to catch and recover from exceptions, as that is how the at() approach reports errors it detects). In comparison, the second approach is considered more dangerous (in the sense of robustness to programmer mistakes, such as making 20 vectors and accessing the 30th one). However, if used incorrectly, any of the approaches can yield invalid behaviour (writing over memory it shouldn't).
    Last edited by grumpy; 12-24-2012 at 11:44 PM.
    Right 98% of the time, and don't care about the other 3%.

  15. #15
    Registered User
    Join Date
    Dec 2012
    Posts
    12
    Thanks for the comprehensive suggestions.
    How does one access an nth element of a vector in the array of vectors?

    Code:
    //say 100th element of ivector = 5
    someVector[5][100]; // is this correct?

Page 1 of 4 1234 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can you create an array/vector of resizable containers?
    By LyTning94 in forum C++ Programming
    Replies: 9
    Last Post: 03-07-2012, 11:50 AM
  2. Faster squaring for a vector of floats
    By onako in forum C++ Programming
    Replies: 6
    Last Post: 09-04-2010, 10:00 AM
  3. can we create instance of a vector?
    By chintugavali in forum C++ Programming
    Replies: 6
    Last Post: 12-20-2007, 11:32 AM
  4. Custom Vector template: Want to create erase/clear function
    By Bird Killer in forum C++ Programming
    Replies: 4
    Last Post: 07-20-2006, 10:37 AM
  5. Call to new to create objects that go into a vector
    By matth in forum C++ Programming
    Replies: 1
    Last Post: 02-11-2006, 01:59 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21