0

我的代码中有一个我无法理解的问题。我想制作一个列表并像二维关联数组一样使用它。

像这样的东西:

token["window"]["title"] = "Amazing!";
cout << token["window"]["title"]; //Amazing!

第二行效果很好。从文件中读取数据。问题在于第一条指令。

这就是我重载第二个方括号的方式:

TokenPair Token::operator[](string keyName){
    for( list<TokenPair>::iterator pair=keys.begin(); pair != keys.end();++pair){
        if(pair->key == keyName){
            return *pair;
        }
    }
}

如您所见,我返回 TokenPair 类的对象。为了正确地从对象(字段 TokenPair::value)中获取值,我在 string() 上重载流式传输和强制转换。

TokenPair::operator string() const{
    return value;
}
ostream & operator<< (ostream &stream, const TokenPair &pair){
    return stream << pair.value;
}

正如我在获得价值之前所说的那样,效果很好。问题在于归因运算符的重载:

TokenPair TokenPair::operator=( const string newValue ){
    value = newValue;
    return *this;
}

这种方法评估价值,但它不记得了!例如:

token["window"]["title"] = "Ok";

将导致内部方法 TokenPair::operator= variable newValue=="Ok"并且在第一行之后,偶数值设置为“Ok”;但是当我后来这样做时:

cout << token["window"]["title"] ;

TokenPair 中的字段仍然没有改变。我想问:为什么?也许迭代器返回该对象的副本?我不知道。请帮忙。

4

2 回答 2

1

您的问题是按值operator[]返回TokenPair,因此在分配时将新值分配给临时值,而不是存储在列表中的对象。

为此,operator[]应返回对要修改的对象的引用。

于 2011-10-31T19:43:33.850 回答
0

以下是如何使用地图地图的示例:

#include <map>
#include <string>
#include <iostream>
#include <sstream>

const char inputString[] =
  "President 16 Lincoln "
  "President 1 Washington "
  "State Best Illinois "
  "State Biggest Alaska ";
int main () {
  std::map<std::string, std::map<std::string, std::string> > token;
  std::string primary, secondary, result;
  std::istringstream input(inputString);
  while( input >> primary >> secondary >> result )
    token[primary][secondary] = result;
  std::cout << "Abe " << token["President"]["16"] << "\n";
  std::cout << "Springfield, " << token["State"]["Best"] << "\n";
  std::cout << "Blank: " << token["President"]["43"] << "\n";
}
于 2011-10-31T21:03:39.583 回答