can I compare 2 vectors by using ==?

K

kathy

I want to compare 2 vectors to see if all element are equal or not:

std::vector <int> v1;
std::vector <int> v2;

v1.push_back(1);
v1.push_back(2);
v1.push_back(3);

v2.push_back(1);
v2.push_back(2);
v2.push_back(2);

if(v1 == v2)
{
// means every item in v1 is equal to every item in v2
}
else
{

}
 
P

panxiangming

vector<int> is can.
but if the data type is you define ,you must overload operation ==.
 
H

hde

Run this and you shall see....... >:-}

#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

int main() {
vector<int> x;
vector<int> y;

x.push_back(1);
x.push_back(2);
x.push_back(3);
x.push_back(4);

y.push_back(1);
y.push_back(2);
y.push_back(3);
y.push_back(4);

if (x == y)
cout << "x == y" << endl;
else
cout << "x != y" << endl;


x.push_back(4);

if (x == y)
cout << "x == y" << endl;
else
cout << "x != y" << endl;

vector<string>a;
vector<string>b;

a.push_back("Foo");
a.push_back("Bar");
a.push_back("Baz");
a.push_back("Quxx");
a.push_back("Quxxx");

b.push_back("Foo");
b.push_back("Bar");
b.push_back("Baz");
b.push_back("Quxx");
b.push_back("Quxxx");

if (a == b)
cout << "a == b" << endl;
else
cout << "a != b" << endl;

b.push_back("Blah");
if (a == b)
cout << "a == b" << endl;
else
cout << "a != b" << endl;

return 0;
}
 
D

Daniel T.

"kathy said:
I want to compare 2 vectors to see if all element are equal or not:

std::vector <int> v1;
std::vector <int> v2;

v1.push_back(1);
v1.push_back(2);
v1.push_back(3);

v2.push_back(1);
v2.push_back(2);
v2.push_back(2);

if(v1 == v2)
{
// means every item in v1 is equal to every item in v2
}
else
{

}

For future reference: <http://www.sgi.com/tech/stl/>

op== tests two vectors for equality. IE the two vectors have the same
size and running "std::equal" over both ranges returns true.
 
D

Daniel T.

Victor Bazarov said:
Why ask when you can simply try?

Kathy is doing the right thing. Simply trying it isn't good enough. Just
because it works on her compiler doesn't mean the standard guarantees it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top