开发者

C++: How to implement (something like) JSON

Not sure how to explain it - I'm pretty new to C++, but... let me try:

Let's say I have 300+ names (Jeff, Jack...) with 300+ int values (0 or 1). In J开发者_Python百科S I would use JSON. Something like this:

var people = {"person": [
              {"name": "Jeff","val": 0},
              {"name": "Jill","val": 1},
              {"name": "Jack","val": 0},
              {"name": "Jim","val": 1},
              {"name": "John","val": 0}
]}

What's the best way to do this in C++? Thanks.


If you can have duplicate names you can't use a map, so you could use something like this:

struct Person
{
  Person( const std::string & n, int v ) : name(n), val(v) {}
  std::string name;
  int val;
};

int main()
{
std::vector<Person> people;

people.push_back( Person( "Jeff", 0 ) );
people.push_back( Person( "Jill", 1 ) );
...

}

If you wanted uniqueness of names you could do something like this:

std::map<std::string, int> people;
people["Jeff"] = 0;
people["Jill"] = 1;

or

std::map<std::string, Person> people;
people["Jeff"] = Person("Jeff",0);
people["Jill"] = Person("Jill",1);

If you're using this code a lot you can clean up the repeated cruft.

template<typename K, typename V>
struct BuildMap
{
  BuildMap() : map_() {}
  BuildMap<K,V>& operator()( const K & key, const V & value )
  {
    map_[key]=value;
    return *this;
  }
  std::map<K,V> operator()() { return map_; }
  std::map<K,V> map_;
};

std::map<std::string,int> people = BuildMap<std::string,int>()
  ( "Jeff", 0 )
  ( "Jill", 1 )
  ( "John", 1 )
  ();

Hope this gives you some ideas.


Take a look at jsoncpp - it is a lightweight json parser, that makes it very easy to use json in your c++ project.

http://sourceforge.net/projects/jsoncpp/

Then you can create a text file, write some entries in the json format there and then open this file in your c++ program. There are plenty of tutorials of how to do it with jsoncpp.


Try looking at std::map.

link here http://www.cplusplus.com/reference/stl/map/

It's an associative container that is similar to a dictionary. Something like this?

#include <map>
#include <string>

std::map<string,int> person;

void initPeople(){
    person["Jeff"] = 0;
    person["Jill"] = 1;
    person["Jack"] = 0;
    person["Jim"] = 1;
    person["John"] = 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜