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; That would be correct. Remember that indices in C++ start at zero. So a vector or array with dimension n ...

  1. #16
    Registered User
    Join Date
    Jun 2005
    Posts
    6,198
    That would be correct. Remember that indices in C++ start at zero. So a vector or array with dimension n has elements with valid indices from 0 to n-1.

    In your example, someVector[5] would correspond to the 6th vector<float> in someVector (0 is first, 1 is second, .... 5 is sixth). someVector[5][100] corresponds to the 101st float within someVector[5]. There is no check by a vector or array as to whether indices are valid, and it is the programmer's responsibility to ensure they are. Hence the use of the at() method which Elysia mentioned - that throws an exception at run time if given an invalid.

    So don't do this
    Code:
       std::vector<std::vector<float> > x(5);
       x[5].push_back(2.0f);
    x[5] does not exist. Invoking x[5].push_back() invokes undefined behaviour according to the C++ standard. Practically, that often tromps some random area of memory, which results in a program crash. However, the compiler cannot check that .... it is the programmer's responsibility.
    Last edited by grumpy; 12-25-2012 at 03:19 AM.
    Right 98% of the time, and don't care about the other 3%.

  2. #17
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,293
    Quote Originally Posted by Elysia View Post
    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.
    In addition to what has been said, I also simply disagree with both of those sentiments. Basically a "learn to float before you learn to swim" sort of argument.

    I think that arguments for std::array are in general pretty weak. The cases where it is of significant benefit tend to be few and far between in reality.
    std::string on the other hand adds a lot of useful functionality, and is worth knowing about sooner rather than later.

    They should probably learn what it is that .at() is protecting them against, because they'll run into raw arrays pretty soon, and what they give up for that protection (*some* amount of performance and extra compilation time).
    You've also worded your argument for .at() poorly, because no matter what you use, it isn't true that you can avoid having to think about out-of-bounds access, in most cases. I.e. if you have an off-by-one then the result is going to be an incorrect program either way. You're gonna have to think about it and get it right sooner or later.
    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"

  3. #18
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,423
    Quote Originally Posted by grumpy View Post
    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.
    But the point is, it was a standard, not just some compiler extension. Any compiler that implements TR1 supports it.

    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.

    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.
    Anything can be misused. But the point is, it is harder to do so, and that is what we want. To catch more errors earlier.
    While we cannot teach newbies all good practices, don'ts and dos, we can at least provide some measures to help them become better programmers, by teaching them of security tools that exist (and refer them to use them by default).
    std::array contains such a security feature, just like vector.

    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.
    Never did it say it complemented the post. In my eyes, it seemed like it was completely disregarding it.
    Had there been some clause saying "In addition, there is this...", then I would have been satisfied (unless, of course, it mandated the use of such features of std::array if such an implementation is available).

    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.
    We are just going to have to learn to disagree on this. Unless there is a particular reason why someone cannot use the latest and greatest, that is what we should teach, IMO.
    Security comes before all, and a newbie should not have to be bothered with this until the time comes to delve into security in depth.

    Quote Originally Posted by iMalc View Post
    I think that arguments for std::array are in general pretty weak. The cases where it is of significant benefit tend to be few and far between in reality.
    std::string on the other hand adds a lot of useful functionality, and is worth knowing about sooner rather than later.
    So you would rather skip std::array simply because it does not any significant benefits? This is a rather silly argument.
    std::array have the iterator concept, size (at both run and compile time if constexpr is supported), and an optional check against out-of-bounds access.
    You want to disregard all this and teach users C arrays, just so later they have to learn std::array (and likely using it by default later)?
    Why not just teach them std::array from the beginning, and save all the trouble?

    They should probably learn what it is that .at() is protecting them against, because they'll run into raw arrays pretty soon, and what they give up for that protection (*some* amount of performance and extra compilation time).
    You've also worded your argument for .at() poorly, because no matter what you use, it isn't true that you can avoid having to think about out-of-bounds access, in most cases. I.e. if you have an off-by-one then the result is going to be an incorrect program either way. You're gonna have to think about it and get it right sooner or later.
    Yes! You should know these things. I am not against that. But you are going to have to remember that this is a topic of security. Security is all-important these days, and should be a formal subject anyone should learn, and not just bits and pieces. So I find this a very good topic to discuss when discussing security in-depth.
    Regardless, if the newbie does not know so much about security, I'd rather have them learn to use .at() than C-arrays with buffer overflows and out-of-bounds access.
    If you want to teach them both worlds, go right ahead. I have no qualms. I simply want std::array to be mentioned as the preferred choice to reduce security risks and make C++ more like other modern languages that do bounds checking.
    On modern computers, bounds checking is cheap. So, unless you really need the extra performance, you should make your program safer by using safer mechanisms. This is what I strongly believe.
    Last edited by Elysia; 12-26-2012 at 05:07 AM.
    Lesshardtofind likes this.
    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.

  4. #19
    Registered User
    Join Date
    Jun 2005
    Posts
    6,198
    Quote Originally Posted by Elysia View Post
    But the point is, it was a standard, not just some compiler extension. Any compiler that implements TR1 supports it.
    If you did a survey of compilers after 2007, you would find that support of TR1 is relatively scarce.

    Quote Originally Posted by Elysia View Post
    Never did it say it complemented the post. In my eyes, it seemed like it was completely disregarding it.
    Had there been some clause saying "In addition, there is this...", then I would have been satisfied (unless, of course, it mandated the use of such features of std::array if such an implementation is available).
    Come off it. I've seen you do exactly the same thing after other people have posted. It is not unusual in forums for someone to answer the original question, without making reference to all preceding answers.

    Quote Originally Posted by Elysia View Post
    We are just going to have to learn to disagree on this. Unless there is a particular reason why someone cannot use the latest and greatest, that is what we should teach, IMO.
    The particular reason I have is history. The C++ standard was in draft for about a decade before it was ratified in 1998. It wasn't until about 2003 (five years later) that any commercially available compiler supported more than 95% of all language or library features. And several vendors commenced development of their compilers in parallel with the standardisation activity (to the extent that compilers from at least three vendors were used as test cases for feasibility of language and library features, while the standard was in draft.

    In fact, there is one language keyword (export) which has only ever been supported by two compiler products (and products derived from those). That feature is now deprecated, and has never been in common use. Imagine if someone kept haranguing people in forums to use "export" in the late 1990s .....

    On that precedent, it is a fair bet that several C++-11 language or library features will not be supported by most compiler products for at least a couple of years (or 2015-2016 if we're pessimistic).

    Teaching a language for which implementations (compilers and libraries) are not yet readily available is actually an effective way to discourage use of newer features. The error messages a compiler will emit if a particular feature is not supported, or only partially supported, tend to discourage using those features again. When implementations become readily available, you will find that experienced practitioners will tend to take up the newer features, and also encourage more use by novices.

    Quote Originally Posted by Elysia View Post
    Security comes before all, and a newbie should not have to be bothered with this until the time comes to delve into security in depth.
    So, you're characterising the .at() method of std::vector and std::array as a security feature? Its default action on a bounds violation (throwing an exception that, by default, causes program termination) might prevent instances of undefined behaviour. From a security standpoint, that is pretty weak. Security assurance generally encompasses preventing invalid accesses, but also providing continuity of correct service (which the default behaviour of .at() does not).

    Quote Originally Posted by Elysia View Post
    So you would rather skip std::array simply because it does not any significant benefits? This is a rather silly argument.
    I would suggest advocating std::array because it is a recently introduced feature is an even sillier argument.

    Quote Originally Posted by Elysia View Post
    std::array have the iterator concept, size (at both run and compile time if constexpr is supported), and an optional check against out-of-bounds access.
    As I said above, that "optional check against out-of-bounds access" is pretty weak from a security perspective.

    If you dig up articles by Andrei Alexandrescu, you will find all sorts of arguments that iterators in the C++ library should be deprecated, in favour of range-based design. He considers that all iterator types are fundamentally unsafe and that, while safe iterators have been written, they come at a high cost in terms of size (of code, or memory usage) and speed.


    Quote Originally Posted by Elysia View Post
    You want to disregard all this and teach users C arrays, just so later they have to learn std::array (and likely using it by default later)?
    Why not just teach them std::array from the beginning, and save all the trouble?
    I don't think anyone has suggested disregarding std::array, except in your mind.

    As a practitioner, I have considered using std::array in production code on a few occasions. Each time I have used something else (mostly in favour of other containers, but once in favour of a C-style array) because the benefits it offers are insignificant. The security benefits you claim are weak (at best) or an illusion that encourages complacency (at worst).

    I would suggest the jury will remain out for some time on the question of whether developers - beginners or otherwise - will use std::array by default. The case, at present, is certainly not yet strong enough to justify it being a preferred choice. And your argument about its security benefits does not hold up.
    Right 98% of the time, and don't care about the other 3%.

  5. #20
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,423
    Security comes before portability, in my mind (unless you otherwise have a good reason). Besides that, three major compilers already supports std::array and a whole lot more. That makes it enough to mention them to newbies. We cannot--must not--worry too much about what comes later for newbies. Maybe they have to maintain old code. Maybe they have to program embedded controllers. Maybe they will use the latest and greatest features in building programs.
    We do not know, nor will we know. The choices are them to teach everything: the safe, the latest and greatest, the unsafe, or to teach one of the paths. And if we teach only one of them, I'd rather concentrate on correct, secure and latest and greatest. If anything, latest and greatest should become all the more relevant in coming years. I cannot mention all the paths or ways, nor can I be bothered to. So I am going to concentrate on the way I think is best. All I wanted from anyone else was to at least mention the latest and greatest instead of throwing newbies down a dangerous and perilous path. Feel free to disagree.
    And again, any security is better than none. Even if .at() is pretty weak in a security standpoint, it still prevents buffer overflows and out-of-bounds reading.
    So we are just going to have to learn to disagree.
    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. #21
    Registered User
    Join Date
    Jun 2005
    Posts
    6,198
    I'm not fussed about you mentioning std::array where it fits, although I consider the premise of your endorsing it remains weak.

    Your position strikes me as hypocritical. On one hand, you can't "be bothered to" mention alternatives to your preferred approach. On the other hand, you demand that everyone else give some form of honourable mention of your preferred approach, and have repeatedly nagged (in this and other threads) anyone who does not.
    Right 98% of the time, and don't care about the other 3%.

  7. #22
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,423
    Demanding and nagging are different things.
    If you don't like something, you speak up. If your view conflicts with others in such a way that you feel you must speak up in several threads, it comes off as nagging. Yes, I nag when I feel I don't agree with others views. This is a discussion forum, after all?
    I don't demand. Everyone is free to take their own approach and have their own mind. I cannot--nor should--push my ideals onto others. I will never tell you to do this or that. But I can nag, and when I feel someone does something wrong, I sometimes do.
    If the one I nag about do not agree, sometimes that one protects his/her own ideals, which leads to discussion. Like this one. Eventually, it ends either when parties agree or cannot agree. Regardless, it does tend to bring about different views of things, which might in itself be a good thing.
    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. #23
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,627
    >> If you don't like something, you speak up.

    Please take responsibility for the C++11 features you demonstrate in your posts. Because if C++11 support is not enabled, you will get errors, like I said. After that, I don't know what happens. Maybe newbies just assume that you don't know what you're talking about and they continue to use the "unsafe" alternatives, thanks to your negligent incompleteness. Mention that C++11 needs to be turned on in the compiler options and which options to flip. Since it's important to you, the easy thing to do would be to make it part of your signature: maybe go through the process on 2 or 3 kinds of compilers somewhere on the net and refer to that. I mean if you believe in something, it's the least you could do for newbies to allow them to actually use your advice.

    Quote Originally Posted by Security Now podcast #364, August 8, 2012
    “‘The tyranny of the default’ [is] the expression I like to use for: we know most users don’t go in and change things. They just assume that someone smarter than them chose the settings that are best for them, and so they say ‘YES’ a lot when they’re asked questions. What that means is that if it’s enabled by default, it’ll tend to stay on.”
    >> If the one I nag about do not agree, sometimes that one protects his/her own ideals, which leads to discussion. Like this one.

    Most are unproductive. I'm don't believe in software engineering "ideals" because I'm jaded, but on top of that, these discussions usually end with nothing accomplished, nothing conceded, and nothing learned.
    Last edited by whiteflags; 12-26-2012 at 10:56 AM.

  9. #24
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,423
    Quote Originally Posted by whiteflags View Post
    Please take responsibility for the C++11 features you demonstrate in your posts. Because if C++11 support is not enabled, you will get errors, like I said. After that, I don't know what happens. Maybe newbies just assume that you don't know what you're talking about and they continue to use the "unsafe" alternatives, thanks to your negligent incompleteness. Mention that C++11 needs to be turned on in the compiler options and which options to flip. Since it's important to you, the easy thing to do would be to make it part of your signature: maybe go through the process on 2 or 3 kinds of compilers somewhere on the net and refer to that. I mean if you believe in something, it's the least you could do for newbies to allow them to actually use your advice.
    A fair advice. I will create SourceForge.net: Cpp11 - cpwiki, then fill it out as best I can, then refer to it in my signature.
    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. #25
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,293
    Quote Originally Posted by Elysia View Post
    So you would rather skip std::array simply because it does not any significant benefits? This is a rather silly argument.
    std::array have the iterator concept, size (at both run and compile time if constexpr is supported), and an optional check against out-of-bounds access.
    You want to disregard all this and teach users C arrays, just so later they have to learn std::array (and likely using it by default later)?
    Why not just teach them std::array from the beginning, and save all the trouble?
    [const] pointers are [const_]iterators. They only lack reverse iterators which are less common.
    The size of an array is always a constant.
    The container makes these things more consistent with other containers, but it doesn't really add much over a plain array. Plain arrays one unfortunately needs to know about because you will always run into those.

    Sure, I should perhaps use std::array more often than I do (which is hardly ever), but they don't realy add anything of value to me in most places I would use them. I do like the idea, but there are still barriers such as being stuck using certain other compilers for embedded devices etc, to me adopting it more fully.
    I might have an array that simply is populated with say a filepath in one API method, and that then goes straight to another API two API calls, and that's all it is used for. I'm not even going to be looking at any of the contents with my own code etc. It's impossible to justify std::array in such a case; You gain nothing whatsoever. Lets get over this blanket rule idea of "use it every time by default". Use whichever is most appropriate for the task at hand. E.g. does it need to work with older compilers?


    Yes! You should know these things. I am not against that. But you are going to have to remember that this is a topic of security. Security is all-important these days, and should be a formal subject anyone should learn, and not just bits and pieces. So I find this a very good topic to discuss when discussing security in-depth.
    Regardless, if the newbie does not know so much about security, I'd rather have them learn to use .at() than C-arrays with buffer overflows and out-of-bounds access.
    If you want to teach them both worlds, go right ahead. I have no qualms. I simply want std::array to be mentioned as the preferred choice to reduce security risks and make C++ more like other modern languages that do bounds checking.
    On modern computers, bounds checking is cheap. So, unless you really need the extra performance, you should make your program safer by using safer mechanisms. This is what I strongly believe.
    You know what, this is all at least convincing me to bring up std::array more than I do. I will try to mention both when it seems appropriate.

    My thoughts for you are though that people will come around. You just need to give them time, and be gentle or you risk having them going the other way out of spite. Plant the seed of the idea, water it lightly every now and then, and let it grow on 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"

  11. #26
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,423
    Quote Originally Posted by iMalc View Post
    The size of an array is always a constant.
    The container makes these things more consistent with other containers, but it doesn't really add much over a plain array. Plain arrays one unfortunately needs to know about because you will always run into those.
    Yes, the size is constant, but the problem is typically to find the size when you have to use it. The added risk of arrays decaying to pointers when passed to functions, making one unable to tell the size doesn't help very much.
    Also, I don't know if this is a bug or intentional, but I have encountered some algorithms in the past where pointers won't work as iterators. std::array, implementing them properly, should work nicely with those.

    ...I do like the idea, but there are still barriers such as being stuck using certain other compilers for embedded devices etc, to me adopting it more fully.
    I might have an array that simply is populated with say a filepath in one API method, and that then goes straight to another API two API calls, and that's all it is used for. I'm not even going to be looking at any of the contents with my own code etc. It's impossible to justify std::array in such a case; You gain nothing whatsoever. Lets get over this blanket rule idea of "use it every time by default". Use whichever is most appropriate for the task at hand. E.g. does it need to work with older compilers?
    All I am trying to say is that whenever you use an array, you should look over your options.
    Can you use std::array? If not, then fine, use C arrays.
    If you can, then ask yourself: is it practical? If all it does is hinder development (as in your example above), then fine, use C arrays.
    But if it doesn't make things worse--or better, if you gain something from it--then please, use it. It's there for a reason.
    Sometimes one might also consider changing C arrays to std::array, too, if it gives sufficient benefits. But at least, if the above line holds true, then at least consider using them.

    My thoughts for you are though that people will come around. You just need to give them time, and be gentle or you risk having them going the other way out of spite. Plant the seed of the idea, water it lightly every now and then, and let it grow on them.
    It is very difficult to know the mindset of someone on a forum. It is also very difficult for others to understand others mindsets. It's so easy to come off arrogant and demanding while in reality one is not. Were it in real life, reactions and body language could be used to distinguish these.
    I try my best to make comments on where I feel things need be added. I try to not sound demanding or insulting, but sometimes it's just hard...
    So if anyone finds me arrogant, demanding or insulting, then know that I do not mean it, even though it may come off as such.
    And sorry to anyone who thinks they've been insulted.
    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.

  12. #27
    Bored Programmer
    Join Date
    Jul 2009
    Location
    Tomball, TX
    Posts
    407
    >> If the one I nag about do not agree, sometimes that one protects his/her own ideals, which leads to discussion. Like this one.

    Most are unproductive. I'm don't believe in software engineering "ideals" because I'm jaded, but on top of that, these discussions usually end with nothing accomplished, nothing conceded, and nothing learned
    I might have to disagree with that. In this one thread I have learned more about std::array than I could have expected to (as I did not know if its existence beforehand). I learn alot from most of ya'lls (ya it says texas on my profile) discussions as each extremely opinionated senior programmer comes along and provides their own view on the topic at hand.

    If you expect to change someone's opinion then yea the discussion is pointless, but if the discussion is for showing new people who stumble on this thread the pros and cons to std::array I think that was achieved very well.

  13. #28
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    681
    Quote Originally Posted by iMalc View Post
    [const] pointers are [const_]iterators. They only lack reverse iterators which are less common.
    A bit offtopic , but pointers can be used as reverse iterators as well (reverse iterators are only wrappers around the regular ones shifted by 1).

    Code:
    int array[5] = { 1, 2, 3, 4, 5 };
    for (std::reverse_iterator<const int*> it(array + 5);
        it != std::reverse_iterator<const int*>(array);
        ++it)
    {
    }
    Quote Originally Posted by Elysia View Post
    It is very difficult to know the mindset of someone on a forum. It is also very difficult for others to understand others mindsets. It's so easy to come off arrogant and demanding while in reality one is not. Were it in real life, reactions and body language could be used to distinguish these.
    I try my best to make comments on where I feel things need be added. I try to not sound demanding or insulting, but sometimes it's just hard...
    So if anyone finds me arrogant, demanding or insulting, then know that I do not mean it, even though it may come off as such.
    And sorry to anyone who thinks they've been insulted.
    That's why you sometimes put an emoticon or something.
    Then it suddenly gives a completely different feeling.
    Am I right?








    ...Am I right?
    Last edited by kmdv; 12-27-2012 at 09:02 AM.
    I never put signature, but I decided to make an exception.

  14. #29
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,627
    You can't accuse someone of teaching bad practices and make it okay with a smilie. The only way to make it OK is to be right. I tell Elysia constantly to pick his battles.

  15. #30
    Registered User
    Join Date
    Dec 2012
    Posts
    12
    I want to complicate the story some more. How does one write an array of array of vectors. Many thanks for the help!
    F.


    Quote Originally Posted by grumpy View Post
    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).

Page 2 of 4 FirstFirst 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