Thread: What is the C++ equivalent for Python...

  1. #16
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by CPlus
    Would the C++ equivalent look something like this?
    No, since you cannot read into a vector like that. By the way, I suggest that you reserve fully capitalised names for macro names. I note that PEP-8 recommends that constants be fully capitalised, thus your naming convention is also unusual in Python.

    This is a roughly equivalent C++ program:
    Code:
    #include <iostream>
    #include <string>
    #include <sstream>
    #include <vector>
    #include <algorithm>
    #include <iterator>
    
    int main()
    {
        using namespace std;
    
        // Read in a list of numbers on a line as a string, e.g., 0 1 2 3 4 5
        cout << "Input your list here: ";
        string line;
        getline(cin, line);
    
        // Extract the numbers from the string into a vector of integers.
        stringstream ss(line);
        vector<int> numbers;
        copy(istream_iterator<int>(ss), istream_iterator<int>(), back_inserter(numbers));
    
        // Append 1
        numbers.push_back(1);
    
        // Print the vector of integers
        copy(numbers.begin(), numbers.end(), ostream_iterator<int>(cout, " "));
        cout << endl;
    }
    This part may be confusing:
    Code:
    stringstream ss(line);
    vector<int> numbers;
    copy(istream_iterator<int>(ss), istream_iterator<int>(), back_inserter(numbers));
    The idea is to treat the line of numbers as an input stream by using a string stream. You can then read from this string stream as if the user entered input from standard input, except that now the line of input has already been read.

    The use of istream_iterator<int> allows one to iterate over the ints of the input stream, using operator>>. back_inserter means that for each int x read, numbers.push_back(x) is performed (i.e., the number read is inserted at the back).
    Last edited by laserlight; 04-01-2010 at 03:50 AM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  2. #17
    Registered User
    Join Date
    Feb 2010
    Posts
    67
    It works

    Much appreciation to all for your patience.
    Sorry haha, I'm learning a lot of languages all at once, so I'm taking notes on how to write a program in each of those languages.

  3. #18
    Registered User
    Join Date
    Feb 2010
    Posts
    67
    Hi guys, I had another quick question:
    Is there any way to do this? (explanation below):
    (what's bolded is what I don't know)

    Code:
    int main()
    {
        cout << "STRING = ";
        string STRING;
        getline(cin, STRING);
    
        stringstream STRINGSTREAM(STRING);
        vector<string> VECTOR;
        copy(istream_iterator<string>(STRINGSTREAM), istream_iterator<string>(), back_inserter(VECTOR));
    
        copy(F(VECTOR,(VECTOR.size() - 1)).begin(), F(VECTOR,(VECTOR.size() - 1)).end(), ostream_iterator<string>(cout, " "));
    }
    
    int F(vector<string> A , int B)
    {
        int counter;
        for (counter==0; counter <= B; counter++)
        {
            A.push_back(STRING[counter]);
        }
    }
    The main() function asks for user input in the form of a string (example: 0 1 a b).

    The string's elements are put inside the vector called VECTOR.

    In main() a function called F(VECTOR,(VECTOR.size() - 1)) is found.
    This comes from F(vector, int) further below in the script.
    For the vector argument, VECTOR is inputted.
    For the int argument, (VECTOR.size() - 1) is inputted.

    Inside the function F(vector, int), STRING[0] all the way to STRING[(VECTOR.size() - 1)] are added to some vector A, which happens to be VECTOR.

    Going back to the main() function, the new VECTOR then gets printed out in main() from beginning to end.

    So if STRING is 0,1,2
    then the final output should be
    0 1 2 STRING[0] STRING[1] STRING[2]
    or
    0 1 2 0 1 2




    How would I do this?

    Thanks for your patience everyone

  4. #19
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by CPlus
    The string's elements are put inside the vector called VECTOR.
    I do not really like to ask people to change their naming convention, but in this case I think I have to insist: stop using fully capitalised names for variables that are not constants. By an almost universal convention in C++, they are reserved for the names of constants, particularly for macro names.

    Quote Originally Posted by CPlus
    In main() a function called F(VECTOR,(VECTOR.size() - 1)) is found.
    This comes from F(vector, int) further below in the script.
    For the vector argument, VECTOR is inputted.
    For the int argument, (VECTOR.size() - 1) is inputted.
    You do not actually have to tell us this: we can easily read this for ourselves.

    Quote Originally Posted by CPlus
    Inside the function F(vector, int), STRING[0] all the way to STRING[(VECTOR.size() - 1)] are added to some vector A, which happens to be VECTOR.
    This is more important, i.e., to tell us what you intend F to do. Furthermore, choose some better name for F.

    Quote Originally Posted by CPlus
    How would I do this?
    To be honest, I am not clear what F is supposed to do. Let's ignore your program: given a vector of strings, and a string, are you trying to append the string to the vector, or are you trying to append each character of the string as a string into the vector?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #20
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by laserlight View Post
    You do not actually have to tell us this: we can easily read this for ourselves.
    Ouch. Don't discourage people from being descriptive!

    To be honest, I am not clear what F is supposed to do.
    Altho the description does kind of fall apart at a certain point.

    Partially that is because of the naming conventions. You (CPlus) may want to do some reading and googling about this. Naming something after a datatype is okay, but not if the name is exactly the same, which is maybe why you resort to capitals (even worse). Like, "string str" is fine in this case.

    Anyway, I'm guessing (because of the ambiguous use of the word) that here STRING refers to STRING from main()
    So if STRING is 0,1,2
    then the final output should be
    0 1 2 STRING[0] STRING[1] STRING[2]
    As you are aware (but do not actually comment on ), the code you posted will not even compile because STRING is out of scope in F().

    I'm further guessing this is because you are coming from python, where you can have code outside of a function* and so perhaps see main() as special, like it has global scope. Nope! main() is scoped like any other function.
    Code:
    string Str;   // global variable
    
    int main() {
         string lstr;   // variable local to main()
    }
    
    void func() {
          string lstr;  // variable local to func()
    }
    There are no statements (code) outside of a function in C/C++. main() is a function. There can be declarations and assignments outside of a function (those are global).

    *which is partially why a python program can be referred to as a script, but C/C++ is not a scripting language this way (get the difference?) and so C/C++ code is never called "a script".
    Last edited by MK27; 04-02-2010 at 06:41 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  6. #21
    Registered User
    Join Date
    Feb 2010
    Posts
    67
    Well the thing is that I know how to add elements to a vector within the same function main().

    What I'm trying to actually do though is make a string vector in main() and use that vector as the input of another function (F in this case, or whatever you want to name it), have F() modify the vector, and print the modified vector inside main().

    I think I made a slight error.
    In the example I gave, if the vector of strings was called sample instead, then F() would append (to that very same vector) the elements sample[0], sample[1], and sample[2].

    After which it would be printed from the function main().

    EDIT: So if the vector sample was originally 0 1 2, then F() would append to that another 0 1 2.
    Thus main() would print 0 1 2 0 1 2 basically.

    I know how to do that using only one function main(), but I was wondering how it could be done using a separate function?

    If clarification is needed, don't hesitate to ask.
    Thanks.
    Last edited by CPlus; 04-02-2010 at 06:49 AM.

  7. #22
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Ah, so what you want to do is to write a function to append to a vector of strings all of its own elements?

    If so, the situation has a caveat: inserting elements into a vector can cause a reallocation, i.e., the internal dynamic array of the vector needs to be expanded (e.g., replaced by a larger one). Unfortunately, reallocation invalidates all references, pointers and iterators referring to elements of the vector.

    One way to avoid reallocation is to use the reserve() member function of vector to ensure we have enough space. We might then use an appropriate insert member function to insert... except that the most appropriate version of insert has as a pre-condition that the iterators of the range to insert are not iterators to the vector.

    One way to avoid this is to resize instead of reserve, but this would not be appropriate if the vector's elements are expensive to default construct, or the element type does not have a default constructor. Still, it should be fine here:
    Code:
    void duplicate(std::vector<std::string>& strings)
    {
        using namespace std;
        const vector<string>::size_type old_size = strings.size();
        strings.resize(old_size * 2);
        const vector<string>::iterator old_end = strings.begin() + old_size;
        copy(strings.begin(), old_end, old_end);
    }
    Notice that I use pass by reference here: this allows the vector in the main function (or whatever function that calls duplicate) to be updated.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #23
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I will encourage you to use better names. F isn't very descriptive, nor is A and B.
    I will provide a modified version to make what you want (not tested to compile):
    Code:
    int main()
    {
        cout << "STRING = ";
        string str;
        getline(cin, str);
    
        stringstream str_stream(str);
        vector<int> vItems;
        copy(istream_iterator<int>(str_stream), istream_iterator<int>(), back_inserter(vItems));
    
        DuplicateAllItems(Items);
    
        copy(Items.begin(), Items.end(), ostream_iterator<int>(cout, " "));
    }
    
    void DuplicateAllItems(vector<int>& Items)
    {
        int OrgSize = Items.size();
        for (int counter = 0; counter < OrgSize; counter++)
        {
            Items.push_back(Items.at(counter));
        }
    }
    For a small explanation:
    You want numbers, ie integers, not strings, so we use int.
    Call DuplicateAllItems to make a copy of all items. We use a reference to make sure we modify the original.
    We store the original size of the vector first, then loop through it by indices (which will never be invalited) and add the items to the end.
    Then we simply copy the output to the screen.

    Your original code was flawed in a number of ways. Here is a list:
    Why pass the size of the vector to the function when the function can query the object itself?
    You must pass by reference if you intend to modify the original; otherwise you will modify a copy.
    F returns an integer! How do you suppose to call the .end() member function on an integer? Furthermore, that asks a little of what you want F to actually return?
    STRING is a local variable in your main function. You can't access it from F. But you do have the vector which has the data, so why do you need the original input string anyway?
    You do not properly initialize the counter. You use comparison (==) instead of assignment (=).
    Your function never returns something even though you specified it returns an int. This is illegal. If you specify that you want to return something, then you must. Otherwise you may specify void as return type to avoid returning anything.
    Last edited by Elysia; 04-02-2010 at 07:08 AM.
    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.

  9. #24
    Registered User
    Join Date
    Feb 2010
    Posts
    67
    EDIT: Oh sorry I just noticed Elysia's post and I'm reading it right now. Everything I wrote below is what I posted before seeing their post.

    Oh well actually appending the same elements twice over to the same vector was random.
    Any new elements appended would work.


    Using some pseudocode, there any way to do this:
    Chronologically, the program would go from red, green, blue.

    Code:
    function1
    {
        string inputted by user
        vector made out of string elements
    
        prints modified vector from function2
    }
    
    function2
    {
        takes vector in function1 and adds elements to it
    }
    Or would I have to define the vector outside of the two functions to make it global first?

  10. #25
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by CPlus View Post
    Or would I have to define the vector outside of the two functions to make it global first?
    No, not as long as you pass by reference as I did in my example.
    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.

  11. #26
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by CPlus View Post
    Or would I have to define the vector outside of the two functions to make it global first?
    No but you must pass by reference, as Elysia indicated. Here I'm just using a single string, but the same is true of a vector.
    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    void func(string &str) {
    	string rep;
    	int len = str.size(), j = 0;
    	rep.resize(len*2);
    	for (int i=0;i<len;i++) {
    		rep[j++] = str[i];
    		rep[j++] = '-';
    	}
    	str = rep;
    }
    
    int main() {
    	string x = "hello world";
    	func(x);
    	cout << x << endl;
    	return 0;
    }
    Using the &reference means that "str" in func() is "x" in main() -- they refer to the same location in physical memory. Without that, "str" would be a copy of x, and so x would not be affected by the changes to str.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  12. #27
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by MK27
    Using the &reference means that "str" in func() is "x" in main()
    I suggest thinking of it as str being of type string& (i.e., reference to string) rather than &reference.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #28
    Registered User
    Join Date
    Jan 2009
    Posts
    103
    Quote Originally Posted by MK27 View Post
    * here is the dereference operator. When used in a declaration(eg, "char *ptr"), the asterisk indicates a pointer to a type.

    I think python uses references but not pointers, so the concept of pointers and dereferencing may be something new.
    Python doesn't even have references (afaik), perl does.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Equivalent of Dos 'copy' in C ?
    By YetBo in forum C Programming
    Replies: 17
    Last Post: 11-04-2009, 10:10 PM
  2. Pointer equivalent to array notation
    By bekkilyn in forum C Programming
    Replies: 4
    Last Post: 12-06-2006, 08:22 PM
  3. Replies: 10
    Last Post: 08-17-2005, 11:17 PM
  4. Header File Question(s)
    By AQWst in forum C++ Programming
    Replies: 10
    Last Post: 12-23-2004, 11:31 PM
  5. Replies: 0
    Last Post: 11-01-2002, 11:56 AM

Tags for this Thread