2014-09-13 61 views
-3

检查整数的特定值向量 ==“比较”操作符可用于向量的工作==矢量 我们可以做到这一点 向量[I] ==值 我有试过这种与整数比较矢量值

if(SolutionMatrix[i]==0) 

这里SolutionMatrix为整型向量

vector<int> SolutionMatrix; 

任何人可以帮助我改编职系这一点。 代码是

for(int index=0;index<SolutionMatrix.size();i++) 
    { 

     vector<int> b(SolutionMatrix[i].size()); 
     vector<int> c(SolutionMatrix[i].size()); 
     int j,k; 
     j=k=0; 

      for(i=0;i<SolutionMatrix[i].size();i++) 
      { 

        if(SolutionMatrix[i]==0) 
        { 
         b[j++]=i; 

        }    
        else 
        { 

         c[k++]=i; 
        } 

      } 
      b.resize(j); 
      c.resize(k); 
} 
+1

你可能会寻找'的std :: find'。但我无法分辨。 – chris 2014-09-13 17:42:57

+0

但它的givig错误.........错误是二进制'==':'class std :: vector >'未定义此运算符或转换为类型可接受预定义的运算符 – Khan 2014-09-13 17:43:49

+1

@Khan显示确切的_relevant_代码 – P0W 2014-09-13 17:45:57

回答

1

如果需要,以确定是否存在是等于给定值,那么就可以使用任一标准算法std::findstd::any_of

例如载体元件

if (std::find(SolutionMatrix.begin(), SolutionMatrix.end(), 0) != SolutionMatrix.end()) 
{ 
    std::cout << "0 is found" << std::endl; 
} 

或者您可以使用基于相同范围的语句。例如

bool found = false;

for (int x : SolutionMatrix) 
{ 
    if (found = x == 0) break; 
} 

if (found) 
{ 
    std::cout << "0 is found" << std::endl; 
} 

编辑:至于你的代码,我的答案后出现,然后我没有看到它的任何意义。在外部循环中,您定义了在每次迭代中将被销毁并重新创建的局部向量b和c。

您可以使用基于相同范围的语句。

例如

#include <iostream> 
#include <vector> 
#include <algorithm> 

int main() 
{ 
    std::vector<int> a = { 1, 0, 2, 0, 0, 4, 5 }; 

    std::vector<int> b; 
    b.reserve(a.size()/2); 
    std::vector<int> c; 
    c.reserve(a.size()/2); 

    size_t i = 0; 

    for (int x : a) 
    { 
     if(x == 0) 
     { 
      b.push_back(i); 
     } 
     else 
     { 
      c.push_back(i); 
     } 

     ++i; 
    } 

    for (int x : a) std::cout << x << ' '; 
    std::cout << std::endl; 

    for (int x : b) std::cout << x << ' '; 
    std::cout << std::endl; 

    for (int x : c) std::cout << x << ' '; 
    std::cout << std::endl; 

    return 0; 
} 

输出是

1 0 2 0 0 4 5 
1 3 4 
0 2 5 6 
+0

其不工作 – Khan 2014-09-13 17:53:37

+0

plz看代码并指导我 – Khan 2014-09-13 17:54:01

+0

你能解释一下这行吗(int x :SolutionMatrix) – Khan 2014-09-13 17:56:31