我已经开始用C++ libcql
库卡珊德拉的工作..我想用C++与libcql库从卡桑德拉检索数据..如何将结果存储在C++中的Map中,然后迭代它并打印出结果?
每当我去使用cqlsh
在命令行上和不选择这样的 -
select record_name, record_value from profile_user where user_id = '1';
我总是在cql命令行上得到以下输出,其中record_name
和record_value实际上是TEXT datatype which is UTF-8 encoded string
的列。
record_name | record_value
-------------+--------------
e1 | hello
e2 | hello
现在来到C++世界 -
现在我试图从C++ libcql library
获取同样的事情...我将运行在以上C++选择查询相同,我想返回一个将有e1, e2 as the key
和HELLO as there value inside that map
的地图...有可能在C++中做到这一点?
/**
* This method will retrieve the data from Cassandra..
* And then call print_rows method to print it out on the console
*/
void get_attributes(string id){
try{
// some code
//Connection open
connection_open();
execute_query("USE testks;");
//this will give me the result back of the select query
cql_result_t& result = execute_query("select * from profile_user where key ='"+id+"';");
// and this is printing it out on the console
print_rows(result);
// some code
} catch (int e){
// some code here
}
}
下面是这将运行我的C++程序后,打印出来的控制台对结果的方法 -
/**
* This method prints out the result on the console.. *
*
*/
void print_rows(cql::cql_result_t& result) {
while (result.next()) {
for (size_t i = 0; i < result.column_count(); ++i) {
cql::cql_byte_t* data = NULL;
cql::cql_int_t size = 0;
result.get_data(i, &data, size);
std::cout.write(reinterpret_cast<char*>(data), size);
std::cout << " | ";
}
std::cout << std::endl;
}
}
,我在控制台上看到运行我的C以上后,结果++程序是一样的东西这 -
e1 | hello |
e2 | hello |
但是我期待的是 - 。结果存储在C++中的地图,以这样的方式使得键应该是e1 and e2
在地图中。并且它们的值应该是HELLO
在同一个Map中...然后迭代Map并在C++中输出结果?这可能与我现有的代码有关吗?
如果是的话,任何人都可以提供一个简单的例子吗?谢谢...
它基本上是一个C++的问题,我猜..只是检索数据,并把它放到地图......但我面临的问题是我的背景是完全在Java中,所以有点困难的时候弄清楚如何做到这一点...
我稍微改变了我的表的设计在这个问题上我原来的问题here,而不是使用集合,我现在使用组合键..
但如果我能找出我以前的问题的解决方案,然后我将采用这种方法,否则我将采用这种方法..
感谢您的帮助......
更新代码: -
随着下面的变化,它总是打印出第一个结果两次?不知道为什么?
void print_rows(cql::cql_result_t& result){
while (result.next()) {
for (size_t i = 0; i < result.column_count(); ++i) {
cql::cql_byte_t* data = NULL;
cql::cql_int_t size = 0;
result.get_data(i, &data, size);
// std::cout.write(reinterpret_cast<char*>(data), size);
// std::cout << " | ";
if(!flag) {
key = reinterpret_cast<char*>(data);
flag = true;
} else if(flag) {
value = reinterpret_cast<char*>(data);
m[key] = value;
flag = false;
}
}
std:map<std::string, std::string>::const_iterator it = m.begin();
for (;it!=m.end(); ++it) {
std::cout << it->first << " : " << it->second << std::endl;
}
std::cout << std::endl;
}
}
e1 : hello
e1 : hello
e2 : hello
我在这里做什么错了?
我唯一的问题是如何将print_rows的结果放入std :: map或无序映射(无论哪一个是高效的),然后迭代它并打印出结果。 – ferhan
可能的重复[将结果存储在C++中的Map中,然后迭代它然后打印出来?](http://stackoverflow.com/questions/19341994/store-the-result-in-a-map-in- c-then-then-iterate-it-and-then-print-out) – Raedwald