Thread: difference between variables and normal text

  1. #1
    Registered User
    Join Date
    Sep 2010
    Posts
    14

    difference between variables and normal text

    Hi, Im having trouble creating struct variables from user imput. Basically what I'm trying to do is for the user to plug in a string and for the program to create an entry within the struct with that string, and later to assign properties to that string. Ill use the tutorial as an example:

    Code:
    struct database {
      int id_number;
      int age;
      float salary;
    };
    
    int main()
    {
      string var;
    
      cout<<"Enter a string.\n";
      getline(cin, STRING);
      
    
      database STRING;  //There is now an employee variable that has modifiable 
                          // variables inside it.
      STRING.age = 22;
      STRING.id_number = 1;
      STRING.salary = 12000.21;
    }
    Any help is much appreciated! Thank you.

  2. #2
    Registered User NeonBlack's Avatar
    Join Date
    Nov 2007
    Posts
    431
    You might want an std::map<string, database>.

    map - C++ Reference
    I copied it from the last program in which I passed a parameter, which would have been pre-1989 I guess. - esbo

  3. #3
    Registered User
    Join Date
    Sep 2010
    Posts
    14
    I'm sorry to bother but can u be a little more explicit as to how I would use that.. (like assigning variables to the STRING in database)...

  4. #4
    Nasal Demon Xupicor's Avatar
    Join Date
    Sep 2010
    Location
    Poland
    Posts
    179
    I think you are talking about "variable variable names", well, you can do something like that in PHP, but not in C++.

    As NeonBlack wrote, look onto std::map, or std::tr1::unordered_map, which is not yet in C++ standard library. unordered_map (C++) - Wikipedia, the free encyclopedia (unordered_map should be faster than map)

    Here you go, an example:
    map - C++ Reference
    And a second one, a bit bloated maybe, but should prove helpful.

    Code:
    #include <iostream>
    #include <map>
    
    class Database {
    public:
        class DbElement {
        protected:
            unsigned int id;
            unsigned int age;
            float salary;
    
        public:
            DbElement() : id(0), age(0), salary(0.0) {}
            DbElement(unsigned int _id, unsigned int _age, float _salary) : id(_id), age(_age), salary(_salary) {}
            ~DbElement() {}
    
            friend std::ostream& operator<<(std::ostream& os, Database::DbElement el) {
                os << "Id: " << el.id << ", age: " << el.age << ", salary: " << el.salary;
                return os;
            }
        };
    
    protected:
        std::map<std::string, DbElement> db;
    
    public:
        Database() {}
        ~Database() {}
    
    //    /**
    //     * Direct R/W access to database elements
    //     */
    //    DbElement& operator[](const std::string& key) {
    //        return db[key];
    //    }
    
        /**
         * Adds the data to database only if given key does not yet exists
         * @return bool - true if the data was added, false if the key already exists
         */
        bool add(const std::string& key, const DbElement& data) {
            if (db.find(key) == db.end()) {
                db[key] = data;
                return true;
            }
            return false;
        }
    
        const DbElement& get(const std::string& key) const {
            return db.at(key);
        }
    
        void print() const {
            for (std::map<std::string, DbElement>::const_iterator i = db.begin(); i != db.end(); ++i) {
                std::cout << "db[\"" << i->first << "\"] == {" << i->second << "}\n";
    
            }
        }
    };
    
    
    
    int main() {
        std::string key;
        Database db;
        
        std::cout << "Please, enter a name for this entry. 'stop' will cause the program to print database and terminate.\n";
        // one word, for a string with spaces and whatnot, use std::getline()
        while (std::cin >> key && key != "stop") {
            db.add(key, Database::DbElement(1, 34, 3200.0));
        }
        db.print();
        
        return 0;
    }
    Be sure to check how std::map's operator[], at() and find() work, those informations are at the manual entry linked earlier.

  5. #5
    Registered User
    Join Date
    Sep 2010
    Posts
    14
    I tried that and I got this error:

    error: 'p1' cannot appear in a constant-expression
    p1 being my variable string.

    I would also be really grateful If the code weren't that sophisticated since I'm only starting to learn C++ and my knowledge isn't that advance.

    Thank you.
    Last edited by kocmohabt33; 09-27-2010 at 07:14 PM.

  6. #6
    Nasal Demon Xupicor's Avatar
    Join Date
    Sep 2010
    Location
    Poland
    Posts
    179
    You'd have to paste some code for us to know why you get the error.

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by kocmohabt33 View Post
    Hi, Im having trouble creating struct variables from user imput. Basically what I'm trying to do is for the user to plug in a string and for the program to create an entry within the struct with that string, and later to assign properties to that string. Ill use the tutorial as an example:
    Code:
    #include <map>
    #include <string>
    
    struct database
    {
    	int id_number;
    	int age;
    	float salary;
    };
    
    std::map<std::string, database> g_Database;
    
    int main()
    {
    	string var;
    
    	cout<<"Enter a string.\n";
    	getline(cin, var);
    	
    	database tmp; //There is now an employee variable that has modifiable 
    											// variables inside it.
    	tmp.age = 22;
    	tmp.id_number = 1;
    	tmp.salary = 12000.21;
    	
    	g_Database[var] = tmp;
    	// Now, to find it, we do:
    	auto it = g_Database.find(var);
    	if (it != g_Database.end()) // If it == g_Database.end(), we didn't find it in the map. read up on iterators.
    	    ;
    }
    Quote Originally Posted by Xupicor View Post
    As NeonBlack wrote, look onto std::map, or std::tr1::unordered_map, which is not yet in C++ standard library. unordered_map (C++) - Wikipedia, the free encyclopedia (unordered_map should be faster than map).
    Not always. std::map is O(logn), but std::unordered_map is something like O(n^2).
    Average performance should be equal or better, however.
    Last edited by Elysia; 09-28-2010 at 01:40 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.

  8. #8
    Banal internet user
    Join Date
    Aug 2002
    Posts
    1,380
    I don't think O(n^2) is right. Most (actually all, IIRC) implementations of unordered_map use hash tables and any sane hash table is going to have linear worst-case performance.

    Be sure to check how std::map's operator[]
    I don't like the way operator[] is used in STL maps. As it stands you use find() for lookup and operator[] for insert. I think using operator[] for lookup and insert() for insert would have been more intuitive. Oh well.
    Last edited by BMJ; 09-28-2010 at 01:06 PM.

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by BMJ View Post
    I don't think O(n^2) is right. Most (actually all, IIRC) implementations of unordered_map use hash tables and any sane hash table is going to have linear worst-case performance.
    Well, that depends on what method they used for building the hash maps. There is not a single method; there are multiple.
    But I admit I don't know the real ordo. In any case, it can be slower than a map, because it has worse worst-case scenario, while std::map is guaranteed O(logn).

    I don't like the way operator[] is used in STL maps. As it stands you use find() for lookup and operator[] for insert. I think using operator[] for lookup and insert() for insert would have been more intuitive. Oh well.
    Agreed.
    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
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I think that before we talk about whether O(n^2) is right, we should talk about the operation. After all, std::map is not O(logn) to begin with. It is a container, not an algorithm. (EDIT: in fact, I think that Elysia mixed up lookup with populating a container, and BMJ assumed that it was about lookup only. O(log n) for lookup for a map is correct, but O(n log n) should be cited for populating a map with n elements. An unordered map should have O(1) lookup in the average case, and O(n) lookup in the worst case, but O(n) time complexity to populate it in the average case, with O(n^2) time complexity to populate it in the worst case.)

    Quote Originally Posted by BMJ
    As it stands you use find() for lookup and operator[] for insert. I think using operator[] for lookup and insert() for insert would have been more intuitive.
    Not exactly. You use find() for lookup, insert() to insert, and operator[] for lookup when you are willing to also accept the insertion of a value initialised object if there is nothing to lookup. This can complicate code, and it can also simplify code.
    Last edited by laserlight; 09-28-2010 at 01:40 PM.
    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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. hi-res vs. normal timer
    By MK27 in forum C Programming
    Replies: 0
    Last Post: 12-02-2009, 08:53 PM
  2. xuni: a Graphical User Interface Widget Toolkit
    By dwks in forum Projects and Job Recruitment
    Replies: 45
    Last Post: 06-04-2008, 02:35 PM
  3. variables and astrisks
    By ulillillia in forum C Programming
    Replies: 4
    Last Post: 05-10-2007, 09:59 AM
  4. conversion from string to variables
    By khaled_helmy in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2004, 07:33 PM
  5. Reading a file to variables
    By BigBadApe in forum C++ Programming
    Replies: 2
    Last Post: 06-29-2002, 04:34 PM