comprehending arrays.

This is a discussion on comprehending arrays. within the C++ Programming forums, part of the General Programming Boards category; Hey guys, I think I jumped the gun a little bit. I wanted to make an array that would allow ...

  1. #1
    NotSoAvgProgrammer
    Join Date
    Jul 2007
    Location
    Virginia, U.S.
    Posts
    57

    comprehending arrays.

    Hey guys, I think I jumped the gun a little bit. I wanted to make an array that would allow me to enter two items, a char and a double, but the program is not working correctly. Here it is.
    Code:
    #include "register.hpp"
    int price;
    char item;
    
    int main()
    {
        std::cout << "Please enter the item: ";
        std::cin >> item;
        std::cout << "Please enter the price: ";
        std::cin >> price;
        map<string, double> mymap;
        mymap.insert("hot dog", 1.95);
        std::cout << std::mymap.find("hot dog");
        return 0;
    }
    The head file has
    Code:
    #include <map>
    #include <iostream>
    But I'm not too concerned as to what I did wrong there anymore. I would rather focus this post more on my comprehension of c++ arrays. So I am going to try to explain arrays from my knowledge and hope that one of you guys can help me better comprehend arrays.

    Code:
    #include <iostream>
    
    int main()
    {
        int array[5];   //  innitiate array so that it reserves the memory for 5 int's.
        int x = 5;
        for (int i = 0; i < 6; i++)       /// set up the basic for loop
    
            {
                array[i] = x;   // array[0-4] = 5-25
                x = x + 5;
    
                std::cout << array[i] << "\n";
            }
    
        return 0;
    }
    Returns 5 - 25

    Multi-dimensional arrays.

    Code:
    #include <iostream>
    
    int main()
    {
        int array[5][5];   //innitiate array, holds 25 intigers.
        int x = 5;
    
        for (int i = 0; i < 6; i++)  // initiat for loop to set first dimension.
    
            {
    
                for (int a = 0; a < 6; a++)  // sets the second dimension
                    {
    
                        array[i][a] = x;    // array[0-5][0-5] = 5-25
    
                        x = x + 5;
    
                        std::cout << array[i][a] << "\n";
                    }
    
            }
    
        return 0;
    }
    Returns 5 - 150

    But when I move on to chars I get confused.

    Code:
    #include <iostream>
    
    int main()
    {
        char array[15];    // also tried with array[2]
    
        array[0] = "hello";        // doesn't that make array[0] "hello"
        array[1] = "world";       // also tried both with single letters ie: "h"; "w";
    
        std::cout << array[0] << " " << array[1];   // should print "hello world"?
    
    
        return 0;
    }
    gives me the error.

    Code:
    Switching to target: default
    Compiling: main.cpp
    main.cpp: In function `int main()':
    main.cpp:7: error: invalid conversion from `const char*' to `char'
    main.cpp:8: error: invalid conversion from `const char*' to `char'
    Process terminated with status 1 (0 minutes, 0 seconds)
    I also tried to turn the words into char hello; char world = "world";.
    Can someone explain what I am doing wrong?
    Also does if anyone would elaborate on anything basic that I did not cover that is a vital piece of information that I can use. I'm sorry if this is a long post and seems quite demanding, but I am unable to take programming until 11th grade, yet I have a yearn to learn it now in attempts to eventually become quite good and be able to make contributions to the open source world.

    I convey my greatest gratitude for you time and effort to help me,

    Joe

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    >> But I'm not too concerned as to what I did wrong there anymore.
    If you were concerned, I'd say use mymap["hot dog"] instead of std::mymap.find("hot dog").

    >> for (int i = 0; i < 6; i++)
    That 6 should be a 5. You want to loop through 0, 1, 2, 3 and 4. The index 5 is out of bounds.

    >> char array[15];
    This is an array of 15 characters. "Hello" is a string, not a character. They are two different things. A string is defined as a sequence of zero or more characters.

    If you really wanted an array of characters, it would look like this:
    Code:
    array[0] = 'h';
    array[1] = 'w';
    std::cout << array[0] << " " << array[1];  // should print "h w".
    If you want to work with strings in C++, use the C++ string class (#include <string>). An array of characters is used in C to hold strings, but is harder to use and more error prone than a C++ string.

    If you take your code and replace char with std::string, then it will work.

  3. #3
    Mad OnionKnight's Avatar
    Join Date
    Jan 2005
    Location
    Umeň, Sweden
    Posts
    555
    A string is an array of characters, not a character. The type for storing them should be char*, which your compiler is hinting at.
    Code:
    char* array[15];
    Be aware that string literals are read-only. Since you're doing C++ a std::string is a better choice.

  4. #4
    Kiss the monkey. CodeMonkey's Avatar
    Join Date
    Sep 2001
    Posts
    907
    No. That is an array of character pointers -- which is a pointer to a pointer.

    Use std::string, and consult this website's pointer tutorials.
    "If you tell the truth, you don't have to remember anything"
    -Mark Twain

  5. #5
    Registered User MacNilly's Avatar
    Join Date
    Oct 2005
    Posts
    326
    You've got 2 different programs going on there. I got confused trying to figure out what you're problem is.

    If it's this...
    Code:
    #include "register.hpp"
    int price;
    char item;
    
    int main()
    {
        std::cout << "Please enter the item: ";
        std::cin >> item;
        std::cout << "Please enter the price: ";
        std::cin >> price;
        map<string, double> mymap;
        mymap.insert("hot dog", 1.95);
        std::cout << std::mymap.find("hot dog");
        return 0;
    }
    I see nothing wrong here...

    Code:
    #include <iostream>
    
    int main()
    {
        int array[5];   //  innitiate array so that it reserves the memory for 5 int's.
        int x = 5;
        for (int i = 0; i < 6; i++)     5 is less that 6, and 5 is out of bounds of the array 0-4  
    
            {
                array[i] = x;   // array[0-4] = 5-25
                x = x + 5;
    
                std::cout << array[i] << "\n";
            }
    
        return 0;
    }
    see comments above

    Same problem in the multi-dim code.

    Basic logic is:

    DECLARE ARRAY OF SIZE INDEX 0 - (SIZE-1)

    FOR COUNT=0 (start), COUNT < (SIZE) (not inclusive to account for 0 index), COUNT++
    ARRAY[COUNT] = BLAH BLAH
    NEXT COUNT

  6. #6
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,806
    Code:
    std::cout << std::mymap.find("hot dog");
    Disregarding the incorrect usage of std:: above, the find member function returns an iterator to the element in the map you are trying to find (or end() if no element is found). For a map, this iterator is a pair<key,value> and has members first (which holds the key) and second (which holds the value). So, to do what you're trying to do you more likely want:
    Code:
    std::cout << (mymap.find("hot dog"))->second; // Outputs 1.95
    ...or the bit of code described by Daved. However, this should only be if you are absolutely sure that the container holds the key in question ("hot dog"). A better way would be checking if the key "hot dog" is present in the container first before you attempt to print out the value stored there:
    Code:
    std::string str("hot dog");
    if( mymap.find(str) != mymap.end() )
        std::cout << mymap[str] << std::endl;
    else
        std::cout << "Could not find key: " << str << std::endl;
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  7. #7
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    >> However, this should only be if you are absolutely sure that the container holds the key in question ("hot dog").

    Not necessarily. It is often the case that you want the container to add a new entry if none exists, and so using mymap["hot dog"] would be appropriate in those cases. It depends on what you want. Although it is important to realize that operator[] will modify the map if the key doesn't exist.

  8. #8
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,806
    Quote Originally Posted by Daved
    >> However, this should only be if you are absolutely sure that the container holds the key in question ("hot dog").

    Not necessarily. It is often the case that you want the container to add a new entry if none exists, and so using mymap["hot dog"] would be appropriate in those cases. It depends on what you want. Although it is important to realize that operator[] will modify the map if the key doesn't exist.
    That was meant for the bit of code I showed above where that particular quote was taken from. If the key is not found, then find will return end() and you shouldn't then try to access the value stored in second. Apologies if that was not clear.
    Last edited by hk_mp5kpdw; 08-16-2007 at 12:51 PM.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,181
    Instead of using mymap[str], I think it would be more efficient to store the iterator returned by mymap.find(str) and then use it.
    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

  10. #10
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    Only if you don't want to add an entry when one doesn't exist. Otherwise it is less efficient.

  11. #11
    NotSoAvgProgrammer
    Join Date
    Jul 2007
    Location
    Virginia, U.S.
    Posts
    57
    I've worked through it and figured out basic arrays. I am now struggling with the comprehension of maps.
    here is my current code.

    Code:
    #include <iostream>
    #include <string>
    #include <map>
    
    int main()
    
        {
            std::map<string, double> menu;    // makes the map menu
            std::string str;                       //makes the string
            std::cin >> str;
    
            menu.insert(str, 1.95);
            menu.insert("french fry", 1.75);
    
            std::cout << "hot dog: " << menu[str];
            std::cout << "french fry: " << menu["french fry"];
    
    
            return 0;
    
        }
    Heres my errors
    Code:
    main.cpp: In function `int main()':
    main.cpp:8: error: `string' undeclared (first use this function)
    main.cpp:8: error: (Each undeclared identifier is reported only once for each function it appears in.)
    main.cpp:8: error: template argument 1 is invalid
    main.cpp:8: error: template argument 3 is invalid
    main.cpp:8: error: template argument 4 is invalid
    main.cpp:8: error: invalid type in declaration before ';' token
    main.cpp:12: error: request for member `insert' in `menu', which is of non-class type `int'
    main.cpp:13: error: request for member `insert' in `menu', which is of non-class type `int'
    main.cpp:15: error: no match for 'operator[]' in 'menu[str]'
    main.cpp:21:6: warning: no newline at end of file
    Process terminated with status 1 (0 minutes, 0 seconds)
    Now what am i not understanding(if you can tell from the code) about maps? Am I doing something simple wrong, or what? I'm always wanting to learn what i know in greater depth, so if you can any leads in that direction would also be greatly apreciate.

    Thanks for any help,


    Joe
    Last edited by avgprogamerjoe; 08-16-2007 at 03:29 PM.

  12. #12
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    You're missing the std namespace in the map declaration:
    Code:
    std::map<std::string, double> menu;
    Last edited by Daved; 08-16-2007 at 03:37 PM.

  13. #13
    ZuK
    ZuK is offline
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Quote Originally Posted by avgprogamerjoe View Post
    Now what am i not understanding
    Namespaces. All this things live in namespace std.
    Kurt

  14. #14
    NotSoAvgProgrammer
    Join Date
    Jul 2007
    Location
    Virginia, U.S.
    Posts
    57
    Code:
    #include <iostream>
    #include <string>
    #include <map>
    
    int main()
    
        {
            std::map<std::string, double> menu;    // makes the map menu
            std::string str("burger");                       //makes the string
    
            menu.insert(str, 1.95);
            menu.insert("french fry", 1.75);
    
            std::cout << "hot dog: " << menu[str];
            std::cout << "french fry: " << menu["french fry"];
    
    
            return 0;
    
        }
    Still gives me errors. Except now it seems like the amount is twice as long.
    Code:
    main.cpp:11: error: no matching function for call to `std::map<std::string, double, std::less<std::string>, std::allocator<std::pair<const std::string, double> > >::insert(std::string&, double)'
    C:/Program Files/CodeBlocks/bin/../lib/gcc/mingw32/3.4.4/../../../../include/c++/3.4.4/bits/stl_map.h:360: note: candidates are: std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, _Alloc>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(const std::pair<const _Key, _Tp>&) [with _Key = std::string, _Tp = double, _Compare = std::less<std::string>, _Alloc = std::allocator<std::pair<const std::string, double> >]
    C:/Program Files/CodeBlocks/bin/../lib/gcc/mingw32/3.4.4/../../../../include/c++/3.4.4/bits/stl_map.h:384: note:                 typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::insert(typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, _Alloc>::iterator, const std::pair<const _Key, _Tp>&) [with _Key = std::string, _Tp = double, _Compare = std::less<std::string>, _Alloc = std::allocator<std::pair<const std::string, double> >]
    main.cpp:12: error: no matching function for call to `std::map<std::string, double, std::less<std::string>, std::allocator<std::pair<const std::string, double> > >::insert(const char[11], double)'
    C:/Program Files/CodeBlocks/bin/../lib/gcc/mingw32/3.4.4/../../../../include/c++/3.4.4/bits/stl_map.h:360: note: candidates are: std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, _Alloc>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(const std::pair<const _Key, _Tp>&) [with _Key = std::string, _Tp = double, _Compare = std::less<std::string>, _Alloc = std::allocator<std::pair<const std::string, double> >]
    C:/Program Files/CodeBlocks/bin/../lib/gcc/mingw32/3.4.4/../../../../include/c++/3.4.4/bits/stl_map.h:384: note:                 typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::insert(typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, _Alloc>::iterator, const std::pair<const _Key, _Tp>&) [with _Key = std::string, _Tp = double, _Compare = std::less<std::string>, _Alloc = std::allocator<std::pair<const std::string, double> >]
    main.cpp:20:6: warning: no newline at end of file
    Process terminated with status 1 (0 minutes, 0 seconds)
    I'm now very confused, what is the significance of "std::"?
    Also, I'm still confused as why the code is not working.


    Joe

  15. #15
    ZuK
    ZuK is offline
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    If you want to insert into a map than you have to insert pairs
    e.g.

    Code:
    menu.insert( std::make_pair(str, 1.95) );
    Kurt

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointers & arrays and realloc!
    By zesty in forum C Programming
    Replies: 14
    Last Post: 01-19-2008, 04:24 PM
  2. Replies: 16
    Last Post: 01-01-2008, 04:07 PM
  3. My Arrays!!!, My Arrays!!! Help!?
    By llcool_d2006 in forum C++ Programming
    Replies: 1
    Last Post: 12-10-2006, 12:07 PM
  4. Need Help With 3 Parallel Arrays Selction Sort
    By slickwilly440 in forum C++ Programming
    Replies: 4
    Last Post: 11-19-2005, 10:47 PM
  5. Crazy memory problem with arrays
    By fusikon in forum C++ Programming
    Replies: 9
    Last Post: 01-15-2003, 09:24 PM

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