简体   繁体   中英

How to initializing std::set<std::string> correctly?

Please help me, I have been trying to do this for the past two-three hours, all with no luck. I have a number of strings comming in form input.txt in the format

string1 string2
string3 string4 
etc.

that I want to put into a std::set which is initially empty. I want to number the strings as they come in and put them into the set to keep track of the duplicates so I don't number them again. I am trying to initialize std::set<std::string> inGraph but can't make it work. I tried to initialize std::set<std::string> inGraph(0, tot_lines); where 0 to tot_lines is the range of the number of total strings I expect to get form the input. The I tried to initialize all with empty stirng like: std::set<std::string> inGraph(tot_lines, ""); and that failed. Here's what I have now:

struct StringInt {
    std::string name;  // associate name and number for each input string
    int number;
};

int main(int argc, char* argv[]) {
int tot_lines = 100;
int icv1, icv2;
std::string vert1, vert2;
std::set<std::string> inGraph();  // this is the set I want to initialize
std::set<std::string>::iterator sit;
std::vector<StringInt> stringInts(tot_lines*2);
StringInt* si;

std::ifstream myfile2 ("input.txt");
  if (myfile2.is_open()) {      
      while(myfile2 >> vert1 >> vert2) {
          // read in input, put it in vars below
          myfile2 >> vert1 >> vert2;  

if (inGraph.find(vert1) != inGraph.end()) {
      icv1 = i++;
      si->name = vert1;
      si->number = icv1;
      inGraph.insert(vert1);
      stringInts.push_back(*si);
  }
  else {
      icv1 = si->number;
  }
  if (inGraph.find(vert2) != inGraph.end()) {
      icv2 = i++;
      si->name = vert1;
      si->number = icv2;
      inGraph.insert(vert2);
      stringInts.push_back(*si);
  }
  else {
      icv2 = si->number;
  }
}

The error I get is: left of '.find' must have class/struct/union Can you please help me figure out how to initialize the std::set<std::string> inGraph so I can number the strings?

The error message is because you are a victim of Most Vexing Parse .

std::set<std::string> inGraph();

It is a function declaration whose return type is std::set<std::string> . Just remove the () after inGraph to make it a object declaration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM