C++ 将向量值与整数进行比较
检查特定值的整数向量 ==“比较”运算符可用于矢量==矢量 我们能这样做吗 向量[i]==值 我试过这个C++ 将向量值与整数进行比较,c++,vector,C++,Vector,检查特定值的整数向量 ==“比较”运算符可用于矢量==矢量 我们能这样做吗 向量[i]==值 我试过这个 if(SolutionMatrix[i]==0) 这里的解矩阵是整数型向量 vector<int> SolutionMatrix; 向量解矩阵; 有谁能帮我重新给这个评分吗。 代码是 for(int index=0;index<SolutionMatrix.size();i++) { vector<int> b(
if(SolutionMatrix[i]==0)
这里的解矩阵是整数型向量
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);
}
for(int index=0;index如果需要确定是否存在等于给定值的向量元素,则可以使用标准算法std::find
或std::任意
比如说
if ( std::find( SolutionMatrix.begin(), SolutionMatrix.end(), 0 ) != SolutionMatrix.end() )
{
std::cout << "0 is found" << std::endl;
}
#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;
}
您可能正在查找std::find
。虽然我说不上来。但它的错误是………错误是二进制的“==”:“class std::vector”没有定义此运算符或到预定义的可接受类型的转换operator@Khan显示确切的相关代码我已添加代码@pow u cansee@KhanSolutionMatrix
不是向量的向量,因此SolutionMatrix[i].size()
是错误的。您能为我解释一下这行代码(int x:SolutionMatrix)是用哪个IDE为(int x:a)为(int x:b)为(int x:c)生成错误的吗@ Khan,我使用了C++ 11的在线编译器。com@Khan您可以使用普通循环,而不是基于范围的for语句。
#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