c++ - 如何按升序编号输入?

标签 c++ string c++11 io

我有输入形式的文件 input.txt 作为两列字符串,例如:

string1 string2
string3 string4
etc.

我试图从 0 开始按升序对字符串进行编号,但重复的字符串不会被分配新值,而是保留已经分配给它们的值。 我决定使用 set::find 操作来执行此操作,但我很难让它工作。这是我到目前为止所拥有的:

int main(int argc, char* argv[]) { 

  std::ifstream myfile ("input.txt");
  std::string line;
  int num = 0;  // num is the total number of input strings

  if (myfile.is_open()) {      
      while(std::getline(myfile, line)) {
          ++num; 
      }
  }

  std::string str1, str1; // strings form input
  int str1Num, str2Num; // numbers assigned to strings

  int i = 0; // used to assign values to strings
  StringInt si;
  std::vector<StringInt> saveStringInts(num);
  std::set<std::string> alreadyCounted(num, 0); 
  std::set<std::string>::iterator sit;

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

    // if strings are not already assigned numbers, assign them
    if ((*(sit = alreadyCounted.find(str1)).compare(str1) != 0) { // doesn't work
      str1Num = i++;
      alreadyCounted.insert(str1);
      saveStringInts.push_back(StringInt(str1Num));
    }
    else {
      str1Num = si->getNum(str1);
    }
    if ((*(sit = alreadyCounted.find(str2)).compare(str2) != 0) { 
      str2Num = i++;
      alreadyCounted.insert(str2);
      saveStringInts.push_back(StringInt(str2Num));
    }
    else {
      str2Num = si->getNum(str2);
    }

    // use str1 and str2 in the functions below before the next iteration


    }
  }

不幸的是,我尝试了其他方法,但现在完全卡住了。如果您知道如何修复我的代码或可以建议更好的方法来完成我的任务,我将非常感谢您的帮助。

最佳答案

你需要比较std::set<int>::iterator针对 end()您的集合的迭代器,而不是取消引用迭代器并将其值与某些东西进行比较!实际上,引用 end()迭代器是未定义的行为:

if ((*(sit = alreadyCounted.find(str1)).compare(str1) != 0) // WRONG: don't do that!

应该是

if (alreadyCounted.find(str1) != alreadyCounted.end())

... 另一个字符串也是如此。不过,就个人而言,我会使用不同的技术:当 insert()进入 std::set<T> ,你会得到一对迭代器和一个对象是否被插入的指示器。后者与当前集合的大小一起给出下一个值,例如:

bool result = alreadyCounted.insert(str1).second;
strNum1 = result? alreadyCounted.size() - 1: si->getNum(str1);

关于c++ - 如何按升序编号输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18688204/

相关文章:

c++ - 正在编译具有相同迭代器的嵌套循环,这是为什么?

c++ - Visual Studio 无法识别 __AVX2__ 或 __AVX__

c++ - 实例化类时是否实例化了类模板的成员?

r - 在 R 中替换单个反斜杠

c++ - 来自另一个非静态的非静态成员初始值设定项

c++ - 如何将 C++ 字符串转换为大写

python - 使用 Python 提取字符串中字符前的数字

c++ - 在 VC++ 中处理字符串的最佳实践?

C++:调用 tuple_transpose 函数时没有匹配的函数调用

c++ - 如何使用具有不同参数的函数作为函数参数