#include <iostream>
#include <sstream>
#include <vector>
#define ii pair<int, int>
using namespace std;

// DSK -> DSC
int n;
vector <ii> edge;
string s, num;

int main()
{
    cin >> n;
    cin.ignore();
    for(int i = 1; i <= n; i++)
    {
        getline(cin, s);
        stringstream ss(s);
        while(ss >> num)
            if(i < stoi(num))
                edge.push_back({i, stoi(num)});
    }
    return 0;
}
error: expected expression
                edge.push_back({i, stoi(num)});
                               ^

How can I fix the 'expected expression' error in my graph code when using VSCode to push a std::pair to a vector?

2

There are 2 best solutions below

0
Sadiq Nayeem On

I think you can use make_pair() function.

edge.push_back(make_pair(i, stoi(num)));
0
selbie On

My psychic powers suggest you are on an older version of C++. Maybe C++11? Not sure which compiler you are using, but there are command line flags that will set the compiler environment to a newer standard than the default.

clang/g++: -std=c++17

MSVC: /std:c++17

Regardless, there's simpler ways to solve this than fighting the compiler. Just make it happy by giving it the type it expects instead of it trying to infer how to coerce your inline params.

For what's really just a couple of ints, this won't incur any performance penalty. And the compiler will likley optimize out the extra copy (if any) in a retail build anyway:

Instead of this:

edge.push_back({i, stoi(num)});

This:

std::pair<int,int> p = {i, stoi(num)};
edge.push_back(p);

Pro-tip unrelated to your quesiton. Always use curly braces for nested statements, even if it's just a single line. It will prevent bugs that easily occur later for not having a block explicitly declared. Instead of this:

        while(ss >> num)
            if(i < stoi(num))
                edge.push_back({i, stoi(num)});

This:

        while(ss >> num)
        {
            if(i < stoi(num))
            {
                edge.push_back({i, stoi(num)});
            }
        }

Putting it altogether:

    while(ss >> num)
    {
        if(i < stoi(num))
        {
            std::pair<int,int> p = {i, stoi(num)};
            edge.push_back(p);
        }
    }

The other answers and comments sugggesting to use make_pair or emplace_back are good suggestions too.