gpt4 book ai didi

c++ - 关于 for_each 用法的 cpp

转载 作者:搜寻专家 更新时间:2023-10-31 01:09:45 25 4
gpt4 key购买 nike

这是我的代码,我想使用 C++ 读取配置文件我的代码在这里:

//myutils.h

#include <string>
#include <map>
using namespace std;

void print(pair<string,string> &p);

void read_login_data(char *login_data,map<string,string> &data_map);

这是 myutils.cpp

//myutils.cpp
#include <fstream>
#include <string>
#include <map>
#include "myutils.h"

using namespace std;

void print(pair<string,string> &p)
{
cout<<p.second<<endl;
}


void read_login_data(char *login_data,map<string,string> &data_map)
{
ifstream infile;
string config_line;
infile.open(login_data);
if (!infile.is_open())
{
cout << "can not open login_data";
return false;

}
stringstream sem;
sem << infile.rdbuf();
while(true)
{
sem >> config_line;
while(config_line)
{
size_t pos = config_line.find('=');
if(pos == npos) continue;
string key = config_line.substr(0,pos);
string value = config_line.substr(pos+1);
data_map[key]=value;

}
}


}

和我的 test.cpp 代码:

#include <iostream>
#include <map>
#include "myutils.h"

using namespace std;

int main()
{
char login[] = "login.ini";
map <string,string> data_map;

read_login_data(login,data_map);
for_each(data_map.begin(),data_map.end(),print);

//cout<< data_map["BROKER_ID"]<<endl;

}

配置文件是:

BROKER_ID=66666
INVESTOR_ID=00017001033

当我使用 :g++ -o test test.cpp myutils.cpp 编译它时,输出是:

young001@server6:~/ctp/ctp_github/trader/src$ g++ -o test test.cpp myutils.cpp
In file included from /usr/include/c++/4.6/algorithm:63:0,
from test.cpp:3:
/usr/include/c++/4.6/bits/stl_algo.h: In function ‘_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = std::_Rb_tree_iterator<std::pair<const std::basic_string<char>, std::basic_string<char> > >, _Funct = void (*)(std::pair<std::basic_string<char>, std::basic_string<char> >&)]’:
test.cpp:15:48: instantiated from here
/usr/include/c++/4.6/bits/stl_algo.h:4379:2: error: invalid initialization of reference of type ‘std::pair<std::basic_string<char>, std::basic_string<char> >&’ from expression of type ‘std::pair<const std::basic_string<char>, std::basic_string<char> >’

好像是pair<>的引用,怎么修改才能生效?

最佳答案

我相信这条线:

void print(pair<string,string> &p)

应该是

void print(pair<const string,string> &p)

在映射中,键值对的“键”部分是常量,只有第二项可以修改。这是在提示你在函数声明中单独读取每一对时没有保持这一点,因此不能保证你保持对的关键部分未被篡改。

编辑:

您的读取循环有点奇怪。我觉得还可以,就是画风不好。我认为这个或类似的东西会更适合您。

while(getline(infile, config_line)) {
size_t pos = config_line.find('=');
if(pos != string::npos) {
string key = config_line.substr(0,pos);
string value = config_line.substr(pos+1);
data_map[key]=value;
} else {
cout << "BAD INPUT PAIR" << endl; //throw exception?
}
}

上面的代码与一个看起来像这样的输入文件一起工作

blah = bigblah
no equals on this one

关于c++ - 关于 for_each 用法的 cpp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16693640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com