C++ 比较向量<string> X 与字符串 S

c++ compare vector<string> x to string s

本文关键字:字符串 gt string 比较 lt C++ 向量      更新时间:2023-10-16

我正在尝试将向量中的一个字符串与另一个字符串进行比较:

我试过了:

vector<string> x;
string y;
if(x[i] == y)
if(x[i].compare(y) == 0)
if(y.compare(x[i]) == 0)
if(x.at(i) == y)
if(x.at(i).compare(y) == 0)
if(y.compare(x.at(i)) == 0)

尝试先将x[i]/x.at(i)传递给string z,但没有任何结果。我没有编译错误,没有问题,只是索引I处的向量似乎不想比较?

g++ -v 4.9.3
Windows 7: cygwin64
c++11, compiling using the -std=c++11 call

我打印出两个字符串,它们是相同的,但它不想比较它们。

-------源cpp

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
vector<string> get_file(const char* file){
      int SIZE=256, ln=0;
      char str[SIZE];
      vector<string> strs;
      ifstream in(file, ios::in);
      if(!in){
        return strs;
      } else {
        while(in.getline(str,SIZE)){
          strs.push_back(string(str));
          ln++;
        }
      }
      in.close();
      return strs;
    }
void convert_file(const char* file){
      vector<string> s = get_file(file);
      vector<string> d;
      int a, b;
      bool t = false;
      for(int i=0; i<s.size(); i++){
        string comp = "--";
        string m = s.at(i);
        cout << m << endl;
        if(m == comp){  //test string compare
          cout << "s[i] == '--'" << endl;
        }
      }
    }
int main(){
  convert_file("dvds.txt");
  return 0;
}

-----dvds.txt

--
title:The Shawshank Redemption
director:Stephan King
release_date:14-10-1994
actors:Tim Robbins,Morgan Freeman,Bob Guton
genres:Crime,Drama
rating:R
price:4.99
--
title:Test title
director:Stephan King
release_date:10-10-1990
actors:Morgan Freeman,random 2,random 4
genres:Adventure,Comedy
rating:PG-13
price:4.99

--
title:Test 3
director:None
release_date:15-52-516
actors:Tim Robbins,None,None 2
genres:Crime,Comedy
rating:PG-17
price:4.99
--

----运行

C:drewprojects>g++ -o a -std=c++11 source.cpp
C:drewprojects>a

打印出dvds.txt很好,但当它应该

时没有进行比较

尝试以下操作:

#include <string>
#include <iostream>
#include <vector>
int main() {
  std::vector<std::string> x;
  std::string y("AAAA");
  x.push_back("AAAA");
  int i = 0;
  if (x[i] == y) {
    std::cout << y << std::endl;
  }

  return 0;
}

这对我很有效。你可能想仔细检查一下你的变量及其类型。您可能还想用不同的编译器尝试同样的操作。