c ++将vector <string> x与string s进行比较

时间:2015-11-27 03:15:46

标签: c++ string c++11 vector string-comparison

我试图将矢量中的字符串与另一个字符串进行比较:

我试过了:

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

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

------- source 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:\drew\projects>g++ -o a -std=c++11 source.cpp
C:\drew\projects>a

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

时没有进行比较

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

#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;
}

它对我有用。您可能想要仔细检查变量及其类型。您可能还希望使用不同的编译器尝试相同的操作。